diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index b3bd2f1298..d895c3969f 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index a674396f4b..c635db0585 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -21,8 +21,9 @@ use std::collections::VecDeque; use std::rc::Rc; use serde_json::{Map, Value, json}; -use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError}; +use vectorcraft_js::{Arg, Data, HostError, HostFunction, LimitKind, Realm, RunError, RunErrorKind}; +use super::scriptui::{self, ScriptUiDialog, Showing, UiEvent, UiStep}; use super::{Host, console}; /// The most bytes (UTF-8) of a dialog's message. @@ -48,6 +49,8 @@ pub enum DialogKind { Alert, Confirm, Prompt, + /// A ScriptUI dialog's `show()` ([`super::scriptui`]). + Window, } impl DialogKind { @@ -57,6 +60,7 @@ impl DialogKind { Self::Alert => "alert", Self::Confirm => "confirm", Self::Prompt => "prompt", + Self::Window => "window", } } } @@ -85,6 +89,8 @@ pub enum DialogAnswer { Confirm(bool), /// OK with the field's text, or Cancel (`None`), for `prompt`. Prompt(Option), + /// What happens in a ScriptUI dialog, step by step, for a run with nobody to ask. + Window(Vec), } impl DialogAnswer { @@ -93,13 +99,14 @@ impl DialogAnswer { Self::Ok => DialogKind::Alert, Self::Confirm(_) => DialogKind::Confirm, Self::Prompt(_) => DialogKind::Prompt, + Self::Window(_) => DialogKind::Window, } } /// What the function returns. fn data(&self) -> Data { match self { - Self::Ok => Data::Undefined, + Self::Ok | Self::Window(_) => Data::Undefined, Self::Confirm(b) => Data::Bool(*b), Self::Prompt(Some(t)) => Data::String(t.clone()), Self::Prompt(None) => Data::Null, @@ -112,6 +119,7 @@ impl DialogAnswer { Self::Ok => json!("ok"), Self::Confirm(b) => json!(b), Self::Prompt(t) => json!(t), + Self::Window(steps) => json!(steps.len()), } } } @@ -148,8 +156,9 @@ pub fn cut_to(text: &str, max: usize) -> &str { } /// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value: -/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter -/// took before dialogs existed, is an empty list. +/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "window", value: [step, ...]}` +/// ([`super::scriptui`]). An empty object, which the parameter took before dialogs existed, is an +/// empty list. pub(crate) fn parse_answers(v: Option<&Value>) -> Result, String> { let list = match v { None => return Ok(Vec::new()), @@ -166,11 +175,18 @@ pub(crate) fn parse_answers(v: Option<&Value>) -> Result, Stri list.iter().enumerate().map(|(i, a)| answer(a).map_err(|e| format!("`answers[{i}]` {e}"))).collect() } -fn answer(a: &Value) -> Result { - let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`") }; +fn answer(a: &Value) -> Result { + let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`".into()) }; if o.len() != 2 || !o.contains_key("value") { - return Err("must have exactly `kind` and `value`"); + return Err("must have exactly `kind` and `value`".into()); } + if o.get("kind").and_then(Value::as_str) == Some("window") { + return super::scriptui::parse_steps(&o["value"]).map(DialogAnswer::Window); + } + known_answer(o).map_err(String::from) +} + +fn known_answer(o: &Map) -> Result { match (o.get("kind").and_then(Value::as_str), &o["value"]) { (Some("alert"), Value::String(s)) if s == "ok" => Ok(DialogAnswer::Ok), (Some("alert"), _) => Err("is an alert's answer, whose `value` must be \"ok\""), @@ -180,7 +196,7 @@ fn answer(a: &Value) -> Result { (Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))), (Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"), (Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"), - _ => Err("must have `kind` alert, confirm or prompt"), + _ => Err("must have `kind` alert, confirm, prompt or window"), } } @@ -199,6 +215,15 @@ pub(crate) struct Dialogs { record_bytes: Cell, count: Cell, truncated: Cell, + /// The ScriptUI dialog whose `show()` is running. + window: RefCell>, + /// Where that dialog's record is in `records`, kept from when it opened so a dialog a handler + /// opens is listed after it; `None` when the list had stopped at its limit. + window_slot: Cell>, + /// That dialog waits for what the person does. + window_waiting: Cell, + /// The `show()` calls the run has made. + shows: Cell, } impl Dialogs { @@ -213,6 +238,10 @@ impl Dialogs { record_bytes: Cell::new(0), count: Cell::new(0), truncated: Cell::new(false), + window: RefCell::default(), + window_slot: Cell::new(None), + window_waiting: Cell::new(false), + shows: Cell::new(0), } } @@ -222,7 +251,176 @@ impl Dialogs { } pub(crate) fn is_waiting(&self) -> bool { - self.waiting.borrow().is_some() + self.waiting.borrow().is_some() || self.window_waiting.get() + } + + /// The ScriptUI dialog that waits for what the person does. + pub(crate) fn waiting_window(&self) -> Option { + if !self.window_waiting.get() { + return None; + } + self.window.borrow().as_ref().map(|s| s.dialog.clone()) + } + + /// The ScriptUI dialog whose `show()` is running, as it last waited, also while a handler runs. + pub(crate) fn showing_window(&self) -> Option { + self.window.borrow().as_ref().map(|s| s.dialog.clone()) + } + + /// Gives the waiting ScriptUI dialog `event`, once it is checked against the dialog. + pub(crate) fn window_answer(&self, realm: &mut Realm, event: UiEvent) -> Result<(), String> { + if !self.window_waiting.get() { + return Err("no script dialog waits".into()); + } + let event = { + let mut window = self.window.borrow_mut(); + let Some(showing) = window.as_mut() else { return Err("no script dialog waits".into()) }; + let event = scriptui::check_event(&showing.dialog, event)?; + showing.events = showing.events.saturating_add(1); + event + }; + self.window_waiting.set(false); + if let Err(e) = realm.answer(event.data()) { + *self.failed.borrow_mut() = Some(e); + } + Ok(()) + } + + fn cannot_wait(&self) -> Result<(), HostError> { + if self.framed && !self.can_wait.get() { + return Err(HostError::Error( + "show: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code" + .into(), + )); + } + Ok(()) + } + + /// `show()` opens `dialog`. A run with nobody to ask takes its next answer, which must be a + /// `window` answer. + pub(crate) fn window_open(&self, mut dialog: ScriptUiDialog) -> Result<(), HostError> { + self.cannot_wait()?; + self.shows.set(self.shows.get().saturating_add(1)); + dialog.shown = self.shows.get(); + let mut showing = Showing { dialog, steps: None, events: 0 }; + if !self.framed { + let next = self.answers.borrow_mut().pop_front(); + match next { + Some(DialogAnswer::Window(steps)) => showing.steps = Some(steps.into()), + Some(a) => { + self.push_record(showing.record(json!("missing"))); + return Err(HostError::Abort(format!("show: the next answer in `answers` is for {}, not window", a.kind().id()))); + } + None => { + self.push_record(showing.record(json!("missing"))); + return Err(HostError::Abort("show: `answers` has no answer left for this dialog".into())); + } + } + } + self.window_slot.set(self.reserve_record()); + *self.window.borrow_mut() = Some(showing); + Ok(()) + } + + /// Keeps a place in the list for the ScriptUI dialog that opens now, counted; its bytes count + /// once the dialog ends. → the place, or `None` when the list stopped at its limit. + fn reserve_record(&self) -> Option { + self.count.set(self.count.get().saturating_add(1)); + let mut records = self.records.borrow_mut(); + if self.truncated.get() || records.len() >= MAX_RECORDS { + self.truncated.set(true); + return None; + } + records.push(Value::Null); + Some(records.len() - 1) + } + + /// Puts the record of the ScriptUI dialog `showing`, with its `answer`, in the place it took + /// in the list when it opened. When the dialogs a handler opened left no room for it, the list + /// drops the last of them until it fits, or stops before the dialog when it does not fit + /// alone, so it still holds the first dialogs in the order they opened, and is marked as + /// stopped at its limit. + fn end_record(&self, showing: &Showing, answer: Value) { + let Some(i) = self.window_slot.take() else { return }; + let size = |r: &Value| serde_json::to_vec(r).map_or(usize::MAX, |b| b.len()); + let r = showing.record(answer); + let bytes = size(&r); + let mut records = self.records.borrow_mut(); + if i >= records.len() { + return; + } + while self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES && records.len() > i + 1 { + let last = records.pop().map_or(0, |r| size(&r)); + self.record_bytes.set(self.record_bytes.get().saturating_sub(last)); + self.truncated.set(true); + } + if self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES { + records.truncate(i); + self.truncated.set(true); + return; + } + self.record_bytes.set(self.record_bytes.get() + bytes); + if let Some(slot) = records.get_mut(i) { + *slot = r; + } + } + + /// The dialog that is showing waits, as `dialog` now is. A run with nobody to ask takes the + /// next step of its answer. + pub(crate) fn window_wait(&self, mut dialog: ScriptUiDialog) -> Result { + self.cannot_wait()?; + let mut window = self.window.borrow_mut(); + let Some(showing) = window.as_mut() else { return Err(HostError::Error("show: no dialog is showing".into())) }; + dialog.shown = showing.dialog.shown; + showing.dialog = dialog; + let Some(steps) = showing.steps.as_mut() else { + drop(window); + self.window_waiting.set(true); + return Err(HostError::Wait); + }; + let failure = match steps.pop_front() { + None => "show: the dialog's answer in `answers` has no step left".to_string(), + Some(step) => match scriptui::step_event(&showing.dialog, &step) { + Ok(event) => { + showing.events = showing.events.saturating_add(1); + return Ok(event.data()); + } + Err(e) => format!("show: a step of the dialog's answer in `answers` cannot be taken: {e}"), + }, + }; + if let Some(showing) = window.take() { + self.end_record(&showing, json!("missing")); + } + Err(HostError::Abort(failure)) + } + + /// `show()` ends with `result`, or with an error when not `normal`. A run with nobody to ask + /// must have used every step of the dialog's answer. + pub(crate) fn window_end(&self, result: f64, normal: bool) -> Result<(), HostError> { + self.window_waiting.set(false); + let Some(showing) = self.window.borrow_mut().take() else { return Ok(()) }; + let left = showing.steps.as_ref().map_or(0, std::collections::VecDeque::len); + let steps = if left == 1 { "step" } else { "steps" }; + let unused = format!("show: the dialog's answer in `answers` has {left} {steps} the dialog did not use"); + if normal && left > 0 { + self.end_record(&showing, json!("missing")); + return Err(HostError::Abort(unused)); + } + // A show that a handler's error ended still ends the run when steps are left: the script + // can catch that error, and the run must not finish as if it took every step. + if left > 0 { + let mut failed = self.failed.borrow_mut(); + if failed.is_none() { + *failed = Some(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message: unused, line: 0, column: 0, authored: false }); + } + } + let answer = match result { + _ if !normal => json!("error"), + r if r.fract() == 0.0 && r.abs() < 9.0e15 => json!(r as i64), + r => json!(r), + }; + self.end_record(&showing, answer); + Ok(()) } /// The error that ended the run when its answer could not reach the script. @@ -257,10 +455,13 @@ impl Dialogs { if let Some(d) = self.waiting.borrow_mut().take() { self.record(&d, json!("stop")); } + self.window_waiting.set(false); + if let Some(showing) = self.window.borrow_mut().take() { + self.end_record(&showing, json!("stop")); + } } fn record(&self, d: &ScriptDialog, answer: Value) { - self.count.set(self.count.get().saturating_add(1)); let mut r = Map::new(); r.insert("kind".into(), json!(d.kind.id())); r.insert("message".into(), json!(d.message)); @@ -269,9 +470,14 @@ impl Dialogs { DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)), DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)), DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)), + DialogKind::Window => None, }; r.insert("answer".into(), answer); - let r = Value::Object(r); + self.push_record(Value::Object(r)); + } + + fn push_record(&self, r: Value) { + self.count.set(self.count.get().saturating_add(1)); let bytes = serde_json::to_vec(&r).map_or(usize::MAX, |b| b.len()); let mut records = self.records.borrow_mut(); if self.truncated.get() || records.len() >= MAX_RECORDS || self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES { @@ -325,6 +531,7 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) }; (text(args, 2), false, false, preset) } + DialogKind::Window => return Err(HostError::Error("a ScriptUI dialog opens with show()".into())), }; if message.len() > MAX_MESSAGE_BYTES { return Err(HostError::Range(format!("{name}: the message is longer than 16 KiB"))); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 1d4978a0d0..bc6ae00250 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -53,8 +53,10 @@ pub mod dialogs; pub mod dollar; pub mod dom; pub mod include; +pub mod scriptui; pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog}; +pub use scriptui::{ScriptUiDialog, UiEvent, UiKind, UiValue}; use std::cell::{Cell, RefCell}; use std::collections::HashMap; @@ -135,7 +137,7 @@ impl Written { /// The version `vc.api.version` gives. pub const API_VERSION: &str = "1.0"; /// The features `vc.api.has` knows. -pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar"]; +pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar", "scriptui"]; /// The most commands a run's report lists in `slowestCommands`. pub const SLOWEST_COMMANDS: usize = 5; @@ -1642,7 +1644,7 @@ fn kind_id(kind: &RunErrorKind) -> &'static str { /// `e`'s message, with what to do about a failure that comes from a script written for another /// program. A message the script supplied itself ([`RunError::authored`]) is given as it is. fn explained(e: &RunError) -> String { - const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"]; + const HOST_OBJECTS: &[&str] = &["BridgeTalk"]; let message = &e.message; let first = message.strip_prefix("ReferenceError: ").and_then(|m| m.split_whitespace().next()); let names_host_object = first.is_some_and(|f| HOST_OBJECTS.contains(&f)); @@ -1908,6 +1910,32 @@ impl Session { with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false) } + /// The ScriptUI dialog the running script's `show()` waits at for what the person does. A run + /// asked to stop no longer waits: the next [`Session::script_pump`] ends it. + pub fn script_window(&self) -> Option { + if self.script_stop.is_set() { + return None; + } + self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting_window())).flatten() + } + + /// The ScriptUI dialog whose `show()` the running script is in, whether it waits at it or runs + /// one of its handlers. A run asked to stop is in none. + pub fn script_window_showing(&self) -> Option { + if self.script_stop.is_set() { + return None; + } + self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.showing_window())).flatten() + } + + /// Gives the ScriptUI dialog the running script waits at `event`; the next + /// [`Session::script_pump`] runs the control's handler. → an error, and the dialog still + /// waits, when nothing waits or the dialog cannot take the event ([`scriptui::check_event`]). + pub fn script_window_answer(&mut self, event: UiEvent) -> std::result::Result<(), String> { + let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return Err("no script dialog waits".into()) }; + with_job(k, |j| j.host.dialogs.window_answer(&mut j.realm, event)).unwrap_or_else(|| Err("no script dialog waits".into())) + } + /// The file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects' /// `openDlg`, `saveDlg` and `selectDlg`) the running script waits at. A run asked to stop no /// longer waits. @@ -2200,6 +2228,7 @@ impl Session { .and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) }) .and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) }) .and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) }) + .and_then(|()| if fresh { scriptui::install(&mut realm, &link) } else { Ok(()) }) .and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) }) .and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() }) .and_then(|()| { @@ -2288,6 +2317,12 @@ impl Session { } job.host.calls_this_slice.set(0); let outcome = run_slice(self, &mut job); + // A failure a dialog recorded in the slice (steps a show left unused) ends the run, even + // when the script went on. + let outcome = match (outcome, job.host.dialogs.take_failure()) { + (Ok(Ok(_)), Some(e)) => Ok(Err(e)), + (outcome, _) => outcome, + }; match outcome { Err(panic) => { let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0, authored: false }; diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs new file mode 100644 index 0000000000..4226196239 --- /dev/null +++ b/crates/engine/src/script/scriptui.rs @@ -0,0 +1,736 @@ +//! ScriptUI dialogs (`new Window("dialog")`, [`vectorcraft_js::scriptui`]): the description a run +//! gives when it shows one, checked and laid out here before the app draws it, and the events the +//! person or `script.run`'s `answers` give back. +//! +//! A description lists the dialog first and each control after the container that holds it. It is +//! refused with an error thrown at `show()` when a control's container comes after it or is not a +//! group or panel, when it holds more than [`MAX_CONTROLS`] controls, nests deeper than +//! [`MAX_DEPTH`], has more than [`MAX_ITEMS`] list items or a text longer than [`MAX_TEXT_BYTES`], +//! names an orientation or an alignment that does not exist, or gives a slider a minimum above its +//! maximum. Sizes, places, spacing and margins are clamped to [`MAX_EXTENT`] pixels, and a slider's +//! or progress bar's value to its range. +//! +//! The layout follows each container's `orientation` (row, column or stack), `alignChildren`, +//! `spacing` and `margins`, a control's `alignment`, `preferredSize` (or `size`), `minimumSize`, +//! `maximumSize` and `bounds` (left, top, right and bottom in its container); a width or height of +//! 0 or less in a size leaves that side to the layout. A control's size comes from its text, items and kind, by +//! VectorCraft's own estimates of a 7-pixel character and a 16-pixel line. The layout is worked out +//! with loops over the list, from the last control to the first for sizes and from the first to the +//! last for places, so a description's nesting takes no native stack. +//! +//! A run with nobody to ask takes one answer from `answers` for each `show()`: `{kind: "window", +//! value: [step, ...]}`, where a step is `{control, event: "click"}`, `{control, event: "change", +//! value}` or `{event: "close"}`. `control` is a control's `name`, or else its text; `value` is an +//! edit field's text, a slider's number, or a list's item index or `null`. Each time the dialog +//! waits it takes the next step; a dialog that waits with no step left, a step for a control the +//! dialog does not hold or cannot take it, and steps left when the dialog closes end the run. +//! +//! The limits here are VectorCraft's own: [`MAX_EXTENT`], and the js crate's [`MAX_CONTROLS`], +//! [`MAX_DEPTH`], [`MAX_ITEMS`] and [`MAX_TEXT_BYTES`]. + +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; + +pub use vectorcraft_js::scriptui::{MAX_CONTROLS, MAX_DEPTH, MAX_ITEMS, MAX_TEXT_BYTES}; + +use super::Host; + +/// The largest size or place, in pixels, of a dialog or a control in it. +pub const MAX_EXTENT: f32 = 8192.0; +/// A character's width and a line's height in VectorCraft's size estimates, in pixels. +const CHAR: f32 = 7.0; +const LINE: f32 = 16.0; + +/// A dialog's element. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UiKind { + Dialog, + Group, + Panel, + StaticText, + EditText, + Button, + CheckBox, + RadioButton, + DropDownList, + ListBox, + Slider, + ProgressBar, +} + +impl UiKind { + fn parse(s: &str) -> Option { + Some(match s { + "dialog" => Self::Dialog, + "group" => Self::Group, + "panel" => Self::Panel, + "statictext" => Self::StaticText, + "edittext" => Self::EditText, + "button" => Self::Button, + "checkbox" => Self::CheckBox, + "radiobutton" => Self::RadioButton, + "dropdownlist" => Self::DropDownList, + "listbox" => Self::ListBox, + "slider" => Self::Slider, + "progressbar" => Self::ProgressBar, + _ => return None, + }) + } + + /// Does it hold controls? + pub fn container(self) -> bool { + matches!(self, Self::Dialog | Self::Group | Self::Panel) + } + + /// Does a click reach it? + pub fn clicks(self) -> bool { + matches!(self, Self::Button | Self::CheckBox | Self::RadioButton) + } +} + +/// How a container places its controls. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Orientation { + Row, + Column, + Stack, +} + +/// Where a control goes across its container: left or top, right or bottom, the middle, or the +/// whole width or height. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Align { + Start, + End, + Center, + Fill, +} + +/// A control's place and size in the dialog, from its top left corner. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct UiRect { + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, +} + +/// One element of a [`ScriptUiDialog`]. +#[derive(Clone, Debug, PartialEq)] +pub struct UiNode { + pub kind: UiKind, + /// 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, + pub text: String, + /// It and every container around it are enabled. + pub enabled: bool, + /// It and every container around it are visible. + pub visible: bool, + /// A check box's or radio button's value. + pub checked: bool, + /// A slider's or progress bar's value, within `min` to `max`. + pub value: f64, + pub min: f64, + pub max: f64, + pub items: Vec, + /// How many times the script replaced a list's items (removed or added some), which tells a + /// list from one that holds the same texts again. + pub items_revision: u64, + pub selection: Option, + pub multiline: bool, + pub readonly: bool, + pub rect: UiRect, + orientation: Orientation, + align_children: (Option, Option), + alignment: (Option, Option), + spacing: f32, + margins: [f32; 4], + size: [Option; 2], + min_size: [Option; 2], + max_size: [Option; 2], + bounds: Option, + /// The characters an edit field or static text reserves room for in its width. + characters: Option, +} + +impl UiNode { + /// How much of a progress bar is done, from 0 to 1. + pub fn fraction(&self) -> f32 { + if self.max <= self.min || self.value <= self.min { + return 0.0; + } + if self.value >= self.max { + return 1.0; + } + let span = self.max - self.min; + // A range wider than the largest number is measured at half scale. + let part = + if span.is_finite() { (self.value - self.min) / span } else { (self.value / 2.0 - self.min / 2.0) / (self.max / 2.0 - self.min / 2.0) }; + part.clamp(0.0, 1.0) as f32 + } +} + +/// A dialog a run shows, checked and laid out. +#[derive(Clone, Debug, PartialEq)] +pub struct ScriptUiDialog { + /// The dialog first, then each control after the container that holds it. + pub nodes: Vec, + /// The button Enter clicks and the one Escape clicks. + pub default_element: Option, + pub cancel_element: Option, + /// Which `show()` of the run this is, counted from 1; 0 before it shows. + pub shown: u64, +} + +impl ScriptUiDialog { + /// The dialog's title. + pub fn title(&self) -> &str { + self.nodes.first().map_or("", |n| n.text.as_str()) + } + + /// The size of the dialog's content. + pub fn size(&self) -> (f32, f32) { + self.nodes.first().map_or((0.0, 0.0), |n| (n.rect.w, n.rect.h)) + } + + /// The first control whose name is `control`, or else the first control without a name + /// whose text is `control`. + pub fn find(&self, control: &str) -> Option { + let by = |name: bool| { + let hit = |n: &UiNode| if name { !control.is_empty() && n.name == control } else { n.name.is_empty() && n.text == control }; + self.nodes.iter().enumerate().skip(1).find(|(_, n)| hit(n)).map(|(i, _)| i) + }; + by(true).or_else(|| by(false)) + } +} + +/// A value a control takes in a change. +#[derive(Clone, Debug, PartialEq)] +pub enum UiValue { + Text(String), + Number(f64), + Index(Option), +} + +/// What the person did with a dialog. +#[derive(Clone, Debug, PartialEq)] +pub enum UiEvent { + /// A click on a button, check box or radio button. + Click(usize), + /// A new value for an edit field, a slider or a list. + Change(usize, UiValue), + /// The dialog's close box. + Close, +} + +impl UiEvent { + /// The event as `show()` takes it. + pub(crate) fn data(&self) -> Data { + let event = |e: &str| ("event".to_string(), Data::String(e.into())); + let id = |i: usize| ("id".to_string(), Data::Number(i as f64)); + match self { + Self::Click(i) => Data::Object(vec![event("click"), id(*i)]), + Self::Change(i, v) => { + let value = match v { + UiValue::Text(t) => Data::String(t.clone()), + UiValue::Number(n) => Data::Number(*n), + UiValue::Index(Some(k)) => Data::Number(*k as f64), + UiValue::Index(None) => Data::Null, + }; + Data::Object(vec![event("change"), id(*i), ("value".into(), value)]) + } + Self::Close => Data::Object(vec![event("close")]), + } + } +} + +/// Checks `event` against `dialog`. → the event as the dialog takes it: a slider's value clamped +/// to its range. +pub fn check_event(dialog: &ScriptUiDialog, event: UiEvent) -> Result { + let id = match &event { + UiEvent::Close => return Ok(event), + UiEvent::Click(i) | UiEvent::Change(i, _) => *i, + }; + let Some(n) = dialog.nodes.get(id).filter(|_| id > 0) else { return Err(format!("the dialog has no control {id}")) }; + if !n.enabled || !n.visible { + return Err(format!("the control {} is disabled or hidden", label(n))); + } + match event { + UiEvent::Click(_) if n.kind.clicks() => Ok(event), + UiEvent::Click(_) => Err(format!("the control {} cannot be clicked", label(n))), + UiEvent::Change(_, UiValue::Text(t)) if n.kind == UiKind::EditText && !n.readonly => { + if t.len() > MAX_TEXT_BYTES { + return Err("the text is longer than 16 KiB".into()); + } + Ok(UiEvent::Change(id, UiValue::Text(t))) + } + UiEvent::Change(_, UiValue::Number(v)) if n.kind == UiKind::Slider && v.is_finite() => { + Ok(UiEvent::Change(id, UiValue::Number(v.clamp(n.min, n.max)))) + } + UiEvent::Change(_, UiValue::Index(k)) if matches!(n.kind, UiKind::DropDownList | UiKind::ListBox) => match k { + Some(k) if k >= n.items.len() => Err(format!("the list {} has no item {k}", label(n))), + k => Ok(UiEvent::Change(id, UiValue::Index(k))), + }, + UiEvent::Change(..) => Err(format!("the control {} cannot take that change", label(n))), + UiEvent::Close => Ok(UiEvent::Close), + } +} + +fn label(n: &UiNode) -> String { + let shown = if n.name.is_empty() { &n.text } else { &n.name }; + super::dialogs::cut_to(shown, 64).to_string() +} + +/// A step of a `window` answer in `script.run`'s `answers`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UiStep { + /// The control's name or text; none for a close. + pub control: Option, + pub event: String, + pub value: Option, +} + +/// The steps of a `window` answer: `[{control, event: "click"} | {control, event: "change", value} +/// | {event: "close"}]`, where `control` is a string of at most 16 KiB and `value` a string, a +/// number or null. +pub(crate) fn parse_steps(v: &Value) -> Result, String> { + let Some(list) = v.as_array() else { return Err("is a window's answer, whose `value` must be a list of steps".into()) }; + list.iter().enumerate().map(|(i, s)| step(s).ok_or_else(|| format!("has a step {i} that is not a valid click, change or close"))).collect() +} + +fn step(s: &Value) -> Option { + let o = s.as_object()?; + if o.keys().any(|k| !matches!(k.as_str(), "control" | "event" | "value")) { + return None; + } + let control = match o.get("control") { + None => None, + Some(Value::String(c)) if c.len() <= MAX_TEXT_BYTES => Some(c.clone()), + Some(_) => return None, + }; + let value = o.get("value").cloned(); + let event = o.get("event").and_then(Value::as_str)?; + let fits = match event { + "close" => control.is_none() && value.is_none(), + "click" => control.is_some() && value.is_none(), + "change" => control.is_some() && matches!(value, Some(Value::String(_) | Value::Number(_) | Value::Null)), + _ => false, + }; + fits.then(|| UiStep { control, event: event.to_string(), value }) +} + +/// The event `step` is for `dialog`. +pub(crate) fn step_event(dialog: &ScriptUiDialog, step: &UiStep) -> Result { + let Some(control) = &step.control else { return Ok(UiEvent::Close) }; + let Some(id) = dialog.find(control) else { return Err(format!("the dialog has no control named {}", super::dialogs::cut_to(control, 64))) }; + let event = match (step.event.as_str(), &step.value) { + ("click", _) => UiEvent::Click(id), + (_, Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())), + (_, Some(Value::Number(n))) if matches!(dialog.nodes[id].kind, UiKind::DropDownList | UiKind::ListBox) => match list_index(n) { + Some(k) => UiEvent::Change(id, UiValue::Index(Some(k))), + None => return Err("a list's `value` must be an item index or null".into()), + }, + (_, Some(Value::Number(n))) => UiEvent::Change(id, UiValue::Number(n.as_f64().unwrap_or(f64::NAN))), + (_, Some(Value::Null)) => UiEvent::Change(id, UiValue::Index(None)), + _ => return Err("a change's `value` must be a string, a number or null".into()), + }; + check_event(dialog, event) +} + +/// A list's item index written as a JSON number: a whole number of 0 or more, as an integer or as +/// a float such as `1.0`; an index past the end stays past it. `None` for a fraction or a negative +/// number. +pub fn list_index(n: &serde_json::Number) -> Option { + if let Some(k) = n.as_u64() { + return Some(usize::try_from(k).unwrap_or(usize::MAX)); + } + let f = n.as_f64()?; + // `as` saturates a whole number too large for usize at usize::MAX. + (f >= 0.0 && f.fract() == 0.0).then_some(f as usize) +} + +fn field<'a>(fields: &'a [(String, Data)], name: &str) -> &'a Data { + fields.iter().find(|(k, _)| k == name).map_or(&Data::Undefined, |(_, v)| v) +} + +fn bad(what: &str) -> HostError { + HostError::Type(format!("show: the dialog's description {what}")) +} + +/// A finite number. +fn number(d: &Data) -> Option { + match d { + Data::Number(n) if n.is_finite() => Some(*n), + _ => None, + } +} + +fn text(d: &Data, what: &str) -> Result { + match d { + Data::String(s) if s.len() <= MAX_TEXT_BYTES => Ok(s.clone()), + Data::String(_) => Err(HostError::Range(format!("show: {what} is longer than 16 KiB"))), + _ => Err(bad(&format!("has no {what}"))), + } +} + +fn extent(n: f64) -> f32 { + (n as f32).clamp(-MAX_EXTENT, MAX_EXTENT) +} + +fn align_name(s: &str, horizontal: Option) -> Result<(Option, Option), HostError> { + let a = match (s, horizontal) { + ("left", Some(true) | None) => (Some(Align::Start), None), + ("right", Some(true) | None) => (Some(Align::End), None), + ("top", Some(false) | None) => (None, Some(Align::Start)), + ("bottom", Some(false) | None) => (None, Some(Align::End)), + ("center", _) => (Some(Align::Center), Some(Align::Center)), + ("fill", _) => (Some(Align::Fill), Some(Align::Fill)), + _ => return Err(HostError::Error(format!("show: there is no alignment {}", super::dialogs::cut_to(s, 64)))), + }; + Ok(match horizontal { + Some(true) => (a.0, None), + Some(false) => (None, a.1), + None => a, + }) +} + +fn alignment(d: &Data) -> Result<(Option, Option), HostError> { + match d { + Data::Null | Data::Undefined => Ok((None, None)), + Data::String(s) => align_name(s, None), + Data::Array(a) if a.len() == 2 => { + let part = |d: &Data, h: bool| match d { + Data::String(s) => align_name(s, Some(h)), + _ => Err(bad("has an alignment that is not a name")), + }; + Ok((part(&a[0], true)?.0, part(&a[1], false)?.1)) + } + _ => Err(bad("has an alignment that is not a name or a pair of names")), + } +} + +fn numbers(d: &Data) -> Result, HostError> { + match d { + Data::Null | Data::Undefined => Ok(None), + Data::Array(a) if a.len() == N => { + let mut out = [0.0; N]; + for (o, v) in out.iter_mut().zip(a) { + *o = number(v).ok_or_else(|| bad("has a size that is not a number"))?; + } + Ok(Some(out)) + } + _ => Err(bad("has a size with the wrong count of numbers")), + } +} + +/// Reads, checks and lays out a dialog's description. +pub fn parse(d: &Data) -> Result { + let Data::Object(top) = d else { return Err(bad("is not an object")) }; + let Data::Array(list) = field(top, "nodes") else { return Err(bad("has no list of controls")) }; + if list.is_empty() { + return Err(bad("has no dialog")); + } + if list.len() > MAX_CONTROLS + 1 { + return Err(HostError::Range(format!("show: a dialog can hold at most {MAX_CONTROLS} controls"))); + } + let mut nodes: Vec = Vec::with_capacity(list.len()); + let mut depth: Vec = Vec::with_capacity(list.len()); + let mut items_total = 0usize; + for (i, n) in list.iter().enumerate() { + let Data::Object(f) = n else { return Err(bad("has a control that is not an object")) }; + let kind = match field(f, "kind") { + Data::String(k) => UiKind::parse(k).ok_or_else(|| bad("has a control of a kind that does not exist"))?, + _ => return Err(bad("has a control without a kind")), + }; + let parent = number(field(f, "parent")).ok_or_else(|| bad("has a control without its container"))?; + let parent = if i == 0 { + if kind != UiKind::Dialog || parent != -1.0 { + return Err(bad("does not start with the dialog")); + } + 0 + } else { + let p = parent as usize; + if parent < 0.0 || parent.fract() != 0.0 || p >= i || kind == UiKind::Dialog { + return Err(bad("has a control before its container")); + } + if !nodes[p].kind.container() { + return Err(bad("has a control inside a control that holds none")); + } + p + }; + let level = if i == 0 { 0 } else { depth[parent] + 1 }; + if level > MAX_DEPTH { + return Err(HostError::Range(format!("show: controls can be nested at most {MAX_DEPTH} deep"))); + } + depth.push(level); + let flag = |name: &str| matches!(field(f, name), Data::Bool(true)); + let (parent_enabled, parent_visible) = if i == 0 { (true, true) } else { (nodes[parent].enabled, nodes[parent].visible) }; + let items = match field(f, "items") { + Data::Array(a) => a.iter().map(|t| text(t, "a list item's text")).collect::, _>>()?, + _ => Vec::new(), + }; + items_total = items_total.saturating_add(items.len()); + if items_total > MAX_ITEMS { + return Err(HostError::Range(format!("show: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + let selection = number(field(f, "selection")).map(|k| k as usize).filter(|k| *k < items.len()); + let (min, max) = (number(field(f, "minvalue")).unwrap_or(0.0), number(field(f, "maxvalue")).unwrap_or(100.0)); + if min > max { + return Err(HostError::Range("show: a slider's or progress bar's minvalue is larger than its maxvalue".into())); + } + let orientation = match field(f, "orientation") { + Data::String(s) if s == "row" => Orientation::Row, + Data::String(s) if s == "column" => Orientation::Column, + Data::String(s) if s == "stack" => Orientation::Stack, + Data::Undefined => Orientation::Column, + _ => return Err(HostError::Error("show: a container's orientation must be row, column or stack".into())), + }; + let bounds = numbers::<4>(field(f, "bounds"))?.map(|[l, t, r, b]| { + let (l, t) = (extent(l), extent(t)); + UiRect { x: l, y: t, w: (extent(r) - l).clamp(0.0, MAX_EXTENT), h: (extent(b) - t).clamp(0.0, MAX_EXTENT) } + }); + // A width or height of 0 or less leaves that side to the layout. + let sides = |name: &str| -> Result<[Option; 2], HostError> { + Ok(numbers::<2>(field(f, name))?.map_or([None, None], |[w, h]| [(w > 0.0).then(|| extent(w)), (h > 0.0).then(|| extent(h))])) + }; + let (size, min_size, max_size) = (sides("size")?, sides("min")?, sides("max")?); + let margins = numbers::<4>(field(f, "margins"))?.map_or([0.0; 4], |m| m.map(|v| extent(v).max(0.0))); + nodes.push(UiNode { + kind, + 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")?, + enabled: flag("enabled") && parent_enabled, + visible: flag("visible") && parent_visible, + checked: flag("value"), + value: number(field(f, "value")).unwrap_or(0.0).clamp(min, max), + min, + max, + items, + items_revision: number(field(f, "itemsRevision")).map_or(0, |n| n as u64), + selection, + multiline: flag("multiline"), + readonly: flag("readonly"), + rect: UiRect::default(), + orientation, + align_children: alignment(field(f, "alignChildren"))?, + alignment: alignment(field(f, "alignment"))?, + spacing: number(field(f, "spacing")).map_or(0.0, |s| extent(s).max(0.0)), + margins, + size, + min_size, + max_size, + bounds, + // At most as many characters as the longest text holds. + characters: number(field(f, "characters")).filter(|c| *c > 0.0).map(|c| (c as f32).min(MAX_TEXT_BYTES as f32)), + }); + } + let target = |name: &str| number(field(top, name)).map(|k| k as usize).filter(|k| nodes.get(*k).is_some_and(|n| n.kind == UiKind::Button)); + let (default_element, cancel_element) = (target("defaultElement"), target("cancelElement")); + let mut dialog = ScriptUiDialog { nodes, default_element, cancel_element, shown: 0 }; + layout(&mut dialog); + Ok(dialog) +} + +/// A control's own size, by VectorCraft's estimates. +fn own_size(n: &UiNode) -> [f32; 2] { + let chars = |s: &str| s.chars().count() as f32; + let widest = |lines: &mut dyn Iterator| lines.map(chars).fold(0.0, f32::max); + let lines = |s: &str| s.lines().count().max(1) as f32; + let longest_item = n.items.iter().map(|t| chars(t)).fold(0.0, f32::max); + // `characters` reserves room for that many characters, however long the text is now. + let reserved = n.characters.unwrap_or(0.0); + match n.kind { + UiKind::StaticText => [widest(&mut n.text.lines()).max(reserved) * CHAR + 4.0, lines(&n.text) * LINE + 4.0], + UiKind::Button => [(chars(&n.text) * CHAR + 24.0).max(80.0), 24.0], + UiKind::CheckBox | UiKind::RadioButton => [chars(&n.text) * CHAR + 24.0, 20.0], + UiKind::EditText if n.multiline => { + [(widest(&mut n.text.lines()).max(reserved) * CHAR + 12.0).max(160.0), lines(&n.text).max(3.0) * LINE + 10.0] + } + UiKind::EditText => [(chars(&n.text).max(reserved) * CHAR + 12.0).max(80.0), 24.0], + UiKind::DropDownList => [(longest_item * CHAR + 40.0).max(100.0), 24.0], + UiKind::ListBox => [(longest_item * CHAR + 24.0).max(120.0), (n.items.len() as f32).clamp(3.0, 10.0) * 18.0 + 6.0], + UiKind::Slider => [160.0, 20.0], + UiKind::ProgressBar => [160.0, 12.0], + UiKind::Dialog | UiKind::Group | UiKind::Panel => [0.0, 0.0], + } +} + +/// Lays the dialog out: each control's size from the last to the first, then each place from the +/// first to the last. +fn layout(d: &mut ScriptUiDialog) { + let n = d.nodes.len(); + let mut kids: Vec> = vec![Vec::new(); n]; + for (i, node) in d.nodes.iter().enumerate().skip(1) { + kids[node.parent].push(i); + } + let mut size = vec![[0.0f32; 2]; n]; + for i in (0..n).rev() { + let node = &d.nodes[i]; + let mut s = if node.kind.container() { + let [l, t, r, b] = node.margins; + let (mut main, mut cross, mut count, mut reach) = (0.0f32, 0.0f32, 0usize, [0.0f32; 2]); + for &k in &kids[i] { + // A hidden control, and everything in it, takes no room. + if !d.nodes[k].visible { + continue; + } + if let Some(bounds) = d.nodes[k].bounds { + reach = [reach[0].max(bounds.x + bounds.w), reach[1].max(bounds.y + bounds.h)]; + continue; + } + let [w, h] = size[k]; + count += 1; + match node.orientation { + Orientation::Row => (main, cross) = (main + w, cross.max(h)), + Orientation::Column => (main, cross) = (main + h, cross.max(w)), + Orientation::Stack => (main, cross) = (main.max(w), cross.max(h)), + } + } + if node.orientation != Orientation::Stack { + main += node.spacing * count.saturating_sub(1) as f32; + } + let (w, h) = match node.orientation { + Orientation::Row | Orientation::Stack => (main, cross), + Orientation::Column => (cross, main), + }; + [(w + l + r).max(reach[0]), (h + t + b).max(reach[1])] + } else { + own_size(node) + }; + for axis in 0..2 { + if let Some(v) = node.size[axis] { + s[axis] = v; + } + if let Some(v) = node.min_size[axis] { + s[axis] = s[axis].max(v); + } + if let Some(v) = node.max_size[axis] { + s[axis] = s[axis].min(v); + } + } + if let Some(b) = node.bounds { + s = [b.w, b.h]; + } + size[i] = [s[0].clamp(0.0, MAX_EXTENT), s[1].clamp(0.0, MAX_EXTENT)]; + } + d.nodes[0].rect = UiRect { x: 0.0, y: 0.0, w: size[0][0], h: size[0][1] }; + for i in 0..n { + if !d.nodes[i].kind.container() { + continue; + } + let node = d.nodes[i].clone(); + let [l, t, r, b] = node.margins; + let (x, y) = (node.rect.x + l, node.rect.y + t); + let (cw, ch) = ((node.rect.w - l - r).max(0.0), (node.rect.h - t - b).max(0.0)); + let mut cursor = 0.0f32; + for &k in &kids[i] { + let kid = &d.nodes[k]; + let rect = if !kid.visible { + UiRect { x, y, w: 0.0, h: 0.0 } + } else if let Some(bounds) = kid.bounds { + UiRect { x: node.rect.x + bounds.x, y: node.rect.y + bounds.y, w: bounds.w, h: bounds.h } + } else { + let [w, h] = size[k]; + 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 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, 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, 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, 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, 0); + let (dy, kh) = place(v_align, h, ch, 1); + UiRect { x: x + dx, y: y + dy, w: kw, h: kh } + } + } + }; + d.nodes[k].rect = UiRect { + x: rect.x.clamp(-MAX_EXTENT, MAX_EXTENT), + y: rect.y.clamp(-MAX_EXTENT, MAX_EXTENT), + w: rect.w.clamp(0.0, MAX_EXTENT), + h: rect.h.clamp(0.0, MAX_EXTENT), + }; + } + } +} + +/// The dialog of one `show()`: the steps left for a run with nobody to ask, and how many events it +/// took. +pub(crate) struct Showing { + pub(crate) dialog: ScriptUiDialog, + pub(crate) steps: Option>, + pub(crate) events: u64, +} + +impl Showing { + /// The report's record of the dialog, with its `answer`: the result of `show()`, `"stop"`, + /// `"missing"` or `"error"`. + pub(crate) fn record(&self, answer: Value) -> Value { + let mut r = Map::new(); + r.insert("kind".into(), json!("window")); + r.insert("title".into(), json!(super::dialogs::cut_to(self.dialog.title(), super::dialogs::MAX_TITLE_BYTES))); + r.insert("controls".into(), json!(self.dialog.nodes.len().saturating_sub(1))); + r.insert("events".into(), json!(self.events)); + r.insert("answer".into(), answer); + Value::Object(r) + } +} + +/// The host function `name` of `Window`, for the run `link` holds. +fn function(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> HostItem { + let l = link.clone(); + HostItem::Function(Rc::new(move |a| f(&*super::current(&l)?, &a))) +} + +/// Adds `Window` to the realm, for the run `link` holds. +pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> { + realm.define_script_ui(vec![("open".into(), function(link, open)), ("wait".into(), function(link, wait)), ("end".into(), function(link, end))]) +} + +fn described(host: &Host, args: &[Data]) -> Result { + host.charge_call(args.iter().map(super::data_size).sum())?; + parse(args.first().unwrap_or(&Data::Undefined)) +} + +fn open(host: &Host, args: &[Data]) -> Result { + let dialog = described(host, args)?; + host.dialogs.window_open(dialog)?; + Ok(Data::Undefined) +} + +fn wait(host: &Host, args: &[Data]) -> Result { + let dialog = described(host, args)?; + host.dialogs.window_wait(dialog) +} + +fn end(host: &Host, args: &[Data]) -> Result { + let result = number(args.first().unwrap_or(&Data::Undefined)).unwrap_or(0.0); + let normal = matches!(args.get(1), Some(Data::Bool(true))); + host.dialogs.window_end(result, normal)?; + Ok(Data::Undefined) +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 892fcf201f..cbfd14550b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -184,6 +184,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_scriptui; mod script_tags; mod script_variables; mod script_xmp; diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index f6da6cb05a..0272e95212 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -165,7 +165,7 @@ fn an_error_names_the_script_its_place_and_kind() { assert_eq!(e, "t.js: line 2, column 3: TypeError: no (thrown)"); let e = run(&mut s, "var = 1;").unwrap_err().to_string(); assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}"); - assert!(run(&mut s, "new Window('dialog');").unwrap_err().to_string().contains("`vc`")); + assert!(run(&mut s, "new BridgeTalk();").unwrap_err().to_string().contains("`vc`")); // The application's members need no `app.`, so naming one alone is not an error. assert_eq!(run(&mut s, "activeDocument;").unwrap()["ok"], true); assert!(run(&mut s, "#targetengine 9x\n1").unwrap_err().to_string().contains("#targetengine needs a name of letters, digits and _")); @@ -206,7 +206,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { assert_eq!(error, Some(json!(format!("t.js:{line}:{column}: {message}"))), "{source}"); } // The app's own reference error names the `vc` object; the same text a script threw does not. - run(&mut s, "new Window('dialog');").unwrap_err(); + run(&mut s, "new BridgeTalk();").unwrap_err(); assert!(s.script_report().unwrap()["message"].as_str().unwrap().contains("`vc`")); assert_eq!(s.script_report().unwrap()["messageOrigin"], "built-in"); // An error in code `eval` compiled keeps where its message came from. diff --git a/crates/engine/src/tests/script_scriptui.rs b/crates/engine/src/tests/script_scriptui.rs new file mode 100644 index 0000000000..23937fb683 --- /dev/null +++ b/crates/engine/src/tests/script_scriptui.rs @@ -0,0 +1,532 @@ +//! ScriptUI dialogs in a script: the description the engine checks and lays out, the `window` +//! answers a run with nobody to ask takes from `answers`, the wait in the app, Stop, and the +//! report's `dialogs`. + +use serde_json::{Value, json}; +use vectorcraft_js::{Data, HostError}; + +use crate::script::scriptui::{self, MAX_CONTROLS, MAX_DEPTH, MAX_EXTENT, MAX_TEXT_BYTES}; +use crate::script::{ScriptUiDialog, UiEvent, UiKind, UiValue}; +use crate::*; + +/// One open document with one rectangle. +fn one_doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s +} + +fn art(s: &Session) -> (String, usize) { + let d = &s.documents()[0]; + (format!("{:?}", d.doc.layers), d.history.undo.len()) +} + +fn headless(s: &mut Session, source: &str, answers: Value) -> Result { + s.execute("script.run", &json!({"source": source, "name": "w.js", "answers": answers})) +} + +/// A run in the app of `source`, one slice in. +fn framed(s: &mut Session, source: &str) { + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "w.js"})).unwrap()["running"], true); + assert!(s.script_pump().is_none()); +} + +/// Pumps the run in the app until it ends or waits at a ScriptUI dialog (`None`). +fn pump(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_window().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +fn window(steps: Value) -> Value { + json!([{"kind": "window", "value": steps}]) +} + +const EDIT: &str = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});"; + +/// A dialog with a field, a check box, a slider, a list and OK and Cancel. +const FORM: &str = "var w = new Window('dialog', 'Settings'); var g = w.add('group'); \ + g.add('statictext', undefined, 'Name:'); var name = g.add('edittext', undefined, 'first', {name: 'name'}); \ + var bold = w.add('checkbox', undefined, 'Bold'); var size = w.add('slider', undefined, 5, 0, 10); size.name = 'size'; \ + var pick = w.add('dropdownlist', undefined, ['a', 'b', 'c']); pick.name = 'pick'; \ + var ok = w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel');"; + +#[test] +fn a_run_with_nobody_to_ask_takes_the_steps_of_its_window_answer() { + let mut s = one_doc(); + let source = format!( + "{EDIT} {FORM} bold.onClick = function () {{ name.text = 'bolded'; }}; var r = w.show(); vc.log([r, name.text, bold.value, size.value, pick.selection.text]);" + ); + let steps = json!([ + {"control": "Bold", "event": "click"}, + {"control": "size", "event": "change", "value": 99}, + {"control": "pick", "event": "change", "value": 2}, + {"control": "OK", "event": "click"}, + ]); + let r = headless(&mut s, &source, window(steps)).unwrap(); + assert_eq!(r["log"], json!([[1, "bolded", true, 10, "c"]]), "the slider's value is clamped to its range: {r}"); + assert_eq!(r["dialogs"], json!([{"kind": "window", "title": "Settings", "controls": 8, "events": 4, "answer": 1}])); + let cancel = headless(&mut s, &format!("{FORM} vc.log(w.show());"), window(json!([{"control": "Cancel", "event": "click"}]))).unwrap(); + assert_eq!(cancel["log"], json!([2])); + let closed = headless(&mut s, &format!("{FORM} vc.log(w.show());"), window(json!([{"event": "close"}]))).unwrap(); + assert_eq!(closed["log"], json!([0])); +} + +#[test] +fn a_dialog_from_a_resource_specification_takes_the_steps_of_its_window_answer() { + let mut s = one_doc(); + let source = "var w = new Window(\"dialog { text: 'Settings', \ + g: Group { label: StaticText { text: 'Name:' }, field: EditText { text: 'first', properties: {name: 'field'} } }, \ + ok: Button { text: 'OK' } }\"); vc.log([w.show(), w.g.field.text]);"; + let steps = json!([{"control": "field", "event": "change", "value": "typed"}, {"control": "OK", "event": "click"}]); + let r = headless(&mut s, source, window(steps)).unwrap(); + assert_eq!(r["log"], json!([[1, "typed"]]), "{r}"); + assert_eq!(r["dialogs"][0]["title"], "Settings"); + assert_eq!(r["dialogs"][0]["controls"], 4); +} + +#[test] +fn a_dialog_a_handler_opens_is_listed_after_the_window_that_opened_it() { + let mut s = one_doc(); + let source = format!("{FORM} bold.onClick = function () {{ alert('Bolded'); }}; vc.log(w.show());"); + let answers = json!([ + {"kind": "window", "value": [{"control": "Bold", "event": "click"}, {"control": "OK", "event": "click"}]}, + {"kind": "alert", "value": "ok"}, + ]); + let r = headless(&mut s, &source, answers).unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["dialogCount"], 2); + assert_eq!(r["dialogs"][0], json!({"kind": "window", "title": "Settings", "controls": 8, "events": 2, "answer": 1}), "{r}"); + assert_eq!((&r["dialogs"][1]["kind"], &r["dialogs"][1]["message"]), (&json!("alert"), &json!("Bolded")), "{r}"); +} + +#[test] +fn a_missing_wrong_or_unused_step_ends_the_run_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + let source = format!("{EDIT} {FORM} try {{ w.show(); }} catch (e) {{ vc.log('caught'); }}"); + for (given, says) in [ + (json!([]), "`answers` has no answer left for this dialog"), + (json!([{"kind": "alert", "value": "ok"}]), "is for alert, not window"), + (window(json!([])), "has no step left"), + (window(json!([{"control": "Nothing", "event": "click"}])), "the dialog has no control named Nothing"), + (window(json!([{"control": "Name:", "event": "click"}])), "cannot be clicked"), + (window(json!([{"control": "pick", "event": "change", "value": 3}])), "has no item 3"), + (window(json!([{"control": "OK", "event": "click"}, {"event": "close"}])), "has 1 step the dialog did not use"), + ] { + let e = headless(&mut s, &source, given.clone()).unwrap_err().to_string(); + assert!(e.contains(says), "{given}: {e}"); + assert_eq!(art(&s), before, "{given}"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!([]), "a missing answer cannot be caught: {report}"); + assert_eq!(report["dialogs"][0]["answer"], "missing", "{report}"); + } +} + +#[test] +fn a_step_names_a_control_by_its_text_only_when_it_has_no_name() { + let mut s = one_doc(); + let source = "var w = new Window('dialog'); \ + var named = w.add('button', undefined, 'Apply', {name: 'apply'}); named.onClick = function () { vc.log('named'); }; \ + var plain = w.add('button', undefined, 'Apply'); plain.onClick = function () { vc.log('plain'); }; \ + w.add('button', undefined, 'OK'); w.show();"; + let steps = window(json!([{"control": "Apply", "event": "click"}, {"control": "apply", "event": "click"}, {"control": "OK", "event": "click"}])); + headless(&mut s, source, steps).unwrap(); + assert_eq!(s.script_report().unwrap()["log"], json!(["plain", "named"])); + let go = "var w = new Window('dialog'); w.add('button', undefined, 'Go', {name: 'go'}); w.show();"; + let e = headless(&mut s, go, window(json!([{"control": "Go", "event": "click"}]))).unwrap_err().to_string(); + assert!(e.contains("the dialog has no control named Go"), "{e}"); + let help = "var w = new Window('dialog'); w.add('button', undefined, 'Help').onClick = function () { vc.log('help'); }; w.show();"; + let e = headless(&mut s, help, window(json!([{"control": "", "event": "click"}]))).unwrap_err().to_string(); + assert!(e.contains("the dialog has no control named"), "an empty step names no control without a name: {e}"); + let blank = "var w = new Window('dialog'); w.add('button', undefined, 'Help').onClick = function () { vc.log('help'); }; \ + w.add('button', undefined, '').onClick = function () { vc.log('blank'); }; w.add('button', undefined, 'OK'); w.show();"; + headless(&mut s, blank, window(json!([{"control": "", "event": "click"}, {"control": "OK", "event": "click"}]))).unwrap(); + assert_eq!(s.script_report().unwrap()["log"], json!(["blank"]), "an empty step names the unnamed control whose text is empty"); +} + +#[test] +fn window_answers_that_do_not_parse_are_refused_before_the_run() { + let mut s = one_doc(); + let bad = |i: usize| format!("`answers[0]` has a step {i} that is not a valid click, change or close"); + for (steps, says) in [ + (json!("click"), "`answers[0]` is a window's answer, whose `value` must be a list of steps".to_string()), + (json!([1]), bad(0)), + (json!([{"event": "close"}, {"event": "tap", "control": "OK"}]), bad(1)), + (json!([{"event": "click"}]), bad(0)), + (json!([{"event": "click", "control": "OK", "value": 1}]), bad(0)), + (json!([{"event": "change", "control": "x"}]), bad(0)), + (json!([{"event": "change", "control": "x", "value": [1]}]), bad(0)), + (json!([{"event": "change", "control": "x".repeat(MAX_TEXT_BYTES + 1), "value": 1}]), bad(0)), + (json!([{"event": "close", "control": "x"}]), bad(0)), + (json!([{"event": "close", "extra": 1}]), bad(0)), + ] { + let e = headless(&mut s, "1", window(steps.clone())).unwrap_err().to_string(); + assert!(e.contains(&says), "{steps}: {e}"); + } +} + +#[test] +fn a_framed_run_waits_at_show_and_runs_each_handler_with_the_persons_events() { + let mut s = one_doc(); + let undo_before = art(&s).1; + framed( + &mut s, + &format!("{EDIT} {FORM} bold.onClick = function () {{ size.enabled = !bold.value; }}; var r = w.show(); vc.log([r, name.text, size.value]);"), + ); + let d = s.script_window().expect("show waits"); + assert_eq!(d.title(), "Settings"); + assert_eq!(d.nodes.len(), 9); + assert_eq!((d.nodes[3].kind, d.nodes[3].text.as_str()), (UiKind::EditText, "first")); + let bold = d.find("Bold").unwrap(); + let size = d.find("size").unwrap(); + assert!(s.script_window_answer(UiEvent::Click(d.find("Name:").unwrap())).is_err(), "static text takes no click"); + assert!(s.script_window_answer(UiEvent::Change(3, UiValue::Text("x".repeat(MAX_TEXT_BYTES + 1)))).is_err()); + assert!(s.script_window_answer(UiEvent::Click(99)).is_err()); + s.script_window_answer(UiEvent::Click(bold)).unwrap(); + assert!(s.script_window_answer(UiEvent::Close).is_err(), "nothing waits until the run goes on"); + assert!(pump(&mut s).is_none()); + let d = s.script_window().unwrap(); + assert!(d.nodes[bold].checked); + assert!(!d.nodes[size].enabled, "the handler disabled the slider"); + assert!(s.script_window_answer(UiEvent::Change(size, UiValue::Number(3.0))).is_err(), "a disabled control takes no events"); + s.script_window_answer(UiEvent::Change(3, UiValue::Text("Ann".into()))).unwrap(); + assert!(pump(&mut s).is_none()); + s.script_window_answer(UiEvent::Click(d.default_element.unwrap())).unwrap(); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[1, "Ann", 5]])); + assert_eq!(r["dialogs"][0]["events"], 3); + assert_eq!(art(&s).1, undo_before + 1, "a finished run is one undo step"); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script"); +} + +#[test] +fn an_unused_step_after_a_handler_threw_ends_the_run_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + let source = format!( + "{EDIT} var w = new Window('dialog'); var f = w.add('button', undefined, 'Fail'); f.onClick = function () {{ throw new Error('boom'); }}; \ + try {{ w.show(); }} catch (e) {{ vc.log('caught'); }}" + ); + let steps = window(json!([{"control": "Fail", "event": "click"}, {"event": "close"}])); + let e = headless(&mut s, &source, steps).unwrap_err().to_string(); + assert!(e.contains("has 1 step the dialog did not use"), "{e}"); + assert_eq!(art(&s), before, "the run is rolled back"); +} + +#[test] +fn a_list_index_written_as_a_whole_float_is_an_index_and_a_fraction_is_refused() { + let mut s = one_doc(); + let source = format!("{FORM} vc.log([w.show(), pick.selection.text]);"); + let r = headless(&mut s, &source, window(json!([{"control": "pick", "event": "change", "value": 1.0}, {"control": "OK", "event": "click"}]))) + .unwrap(); + assert_eq!(r["log"], json!([[1, "b"]])); + let e = headless(&mut s, &source, window(json!([{"control": "pick", "event": "change", "value": 1.5}]))).unwrap_err().to_string(); + assert!(e.contains("a list's `value` must be an item index or null"), "{e}"); +} + +#[test] +fn a_progress_bar_s_fraction_stays_finite_over_the_widest_range() { + let bar = |min: f64, max: f64, value: f64| { + let n = + with(with(with(node("progressbar", 0.0), "minvalue", Data::Number(min)), "maxvalue", Data::Number(max)), "value", Data::Number(value)); + scriptui::parse(&description(vec![node("dialog", -1.0), n])).unwrap().nodes[1].fraction() + }; + assert_eq!(bar(-1e308, 1e308, 1e308), 1.0); + assert_eq!(bar(-1e308, 1e308, -1e308), 0.0); + assert_eq!(bar(-1e308, 1e308, 0.0), 0.5); + assert_eq!(bar(0.0, 10.0, 3.0), 0.3); + assert_eq!(bar(5.0, 5.0, 5.0), 0.0, "an empty range shows nothing done"); +} + +#[test] +fn stop_while_show_waits_ends_the_run_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + framed(&mut s, &format!("{EDIT} {FORM} w.show(); vc.log('after');")); + assert!(s.script_window().is_some()); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert_eq!(s.script_window(), None, "a run asked to stop no longer waits"); + assert!(s.script_window_answer(UiEvent::Close).is_err()); + assert!(s.script_pump().unwrap().is_err()); + let report = s.script_report().unwrap(); + assert_eq!((report["kind"].as_str(), &report["log"]), (Some("stopped"), &json!([])), "{report}"); + assert_eq!(report["dialogs"][0]["answer"], "stop"); + assert_eq!(art(&s), before); + framed(&mut s, &format!("{EDIT} {FORM} w.show();")); + assert!(s.script_abandon(), "quitting while a dialog waits abandons the run"); + assert_eq!(art(&s), before); +} + +#[test] +fn a_handler_that_loops_ends_the_run_at_its_fuel_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + let source = format!("{EDIT} {FORM} bold.onClick = function () {{ for (;;) {{}} }}; w.show();"); + let e = headless(&mut s, &source, window(json!([{"control": "Bold", "event": "click"}]))).unwrap_err().to_string(); + assert!(e.contains("limit") || e.contains("fuel") || e.contains("instructions"), "{e}"); + assert_eq!(art(&s), before); + assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "error"); +} + +#[test] +fn a_show_in_a_callback_throws_in_the_app() { + let mut s = one_doc(); + s.script_frames = true; + let source = "var w = new Window('dialog'); w.add('button', undefined, 'OK'); var e = ''; try { [1].forEach(function () { w.show(); }); } catch (x) { e = x.message; } vc.log(e);"; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "w.js"})).unwrap()["running"], true); + let r = pump(&mut s).expect("show does not wait in a callback").unwrap(); + assert!(r["log"][0].as_str().unwrap().contains("cannot open inside a callback"), "{r}"); +} + +/// A handler that `notify` runs while no dialog is showing may show one in a run with nobody to +/// ask, which takes a window answer for it; in the app the same `show()` throws. +#[test] +fn a_show_in_a_handler_notify_runs_takes_a_window_answer_with_nobody_to_ask() { + let source = "var b = new Window('dialog').add('button', undefined, 'Go'); var r = ''; \ + b.onClick = function () { var d = new Window('dialog'); d.add('button', undefined, 'OK'); r = d.show(); }; \ + try { b.notify(); } catch (x) { r = x.message; } vc.log(r);"; + let mut s = one_doc(); + let r = headless(&mut s, source, window(json!([{"control": "OK", "event": "click"}]))).unwrap(); + assert_eq!(r["log"], json!([1]), "{r}"); + let mut s = one_doc(); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "w.js"})).unwrap()["running"], true); + let r = pump(&mut s).expect("show does not wait in a handler notify runs").unwrap(); + assert!(r["log"][0].as_str().unwrap().contains("cannot open inside a callback"), "{r}"); +} + +fn node(kind: &str, parent: f64) -> Data { + Data::Object(vec![ + ("kind".into(), Data::String(kind.into())), + ("parent".into(), Data::Number(parent)), + ("name".into(), Data::String(String::new())), + ("text".into(), Data::String("t".into())), + ("enabled".into(), Data::Bool(true)), + ("visible".into(), Data::Bool(true)), + ]) +} + +fn description(nodes: Vec) -> Data { + Data::Object(vec![ + ("nodes".into(), Data::Array(nodes)), + ("defaultElement".into(), Data::Number(-1.0)), + ("cancelElement".into(), Data::Number(-1.0)), + ]) +} + +fn with(n: Data, name: &str, value: Data) -> Data { + let Data::Object(mut fields) = n else { panic!("a node is an object") }; + fields.retain(|(k, _)| k != name); + fields.push((name.into(), value)); + Data::Object(fields) +} + +fn refused(d: &Data) -> String { + match scriptui::parse(d) { + Err(HostError::Type(m) | HostError::Range(m) | HostError::Error(m)) => m, + other => panic!("not refused: {other:?}"), + } +} + +#[test] +fn a_description_out_of_order_too_large_too_deep_or_too_long_is_refused() { + let dialog = node("dialog", -1.0); + assert!(refused(&description(vec![])).contains("has no dialog")); + assert!(refused(&description(vec![node("group", -1.0)])).contains("does not start with the dialog")); + assert!(refused(&description(vec![dialog.clone(), node("button", 2.0), node("group", 0.0)])).contains("before its container")); + assert!(refused(&description(vec![dialog.clone(), node("button", 1.0)])).contains("before its container"), "a control cannot hold itself"); + assert!(refused(&description(vec![dialog.clone(), node("button", 0.0), node("button", 1.0)])).contains("holds none")); + assert!(refused(&description(vec![dialog.clone(), node("dialog", 0.0)])).contains("before its container")); + let many: Vec = std::iter::once(dialog.clone()).chain((0..=MAX_CONTROLS).map(|_| node("button", 0.0))).collect(); + assert!(refused(&description(many)).contains(&format!("at most {MAX_CONTROLS} controls"))); + let deep: Vec = std::iter::once(dialog.clone()).chain((0..=MAX_DEPTH).map(|k| node("group", k as f64))).collect(); + assert!(refused(&description(deep)).contains(&format!("at most {MAX_DEPTH} deep"))); + let long = with(node("statictext", 0.0), "text", Data::String("x".repeat(MAX_TEXT_BYTES + 1))); + assert!(refused(&description(vec![dialog.clone(), long])).contains("longer than 16 KiB")); + let slider = with(with(node("slider", 0.0), "minvalue", Data::Number(5.0)), "maxvalue", Data::Number(1.0)); + assert!(refused(&description(vec![dialog.clone(), slider])).contains("minvalue is larger")); + let nan = with(node("button", 0.0), "bounds", Data::Array(vec![Data::Number(0.0), Data::Number(f64::NAN), Data::Number(1.0), Data::Number(1.0)])); + assert!(refused(&description(vec![dialog.clone(), nan])).contains("not a number")); + let orient = with(dialog.clone(), "orientation", Data::String("diagonal".into())); + assert!(refused(&description(vec![orient])).contains("row, column or stack")); + let align = with(node("button", 0.0), "alignment", Data::String("sideways".into())); + assert!(refused(&description(vec![dialog, align])).contains("no alignment sideways")); +} + +#[test] +fn sizes_and_places_are_clamped_and_the_layout_follows_the_containers() { + let dialog = with(with(node("dialog", -1.0), "orientation", Data::String("column".into())), "margins", Data::Array(vec![Data::Number(10.0); 4])); + let row = with(with(node("group", 0.0), "orientation", Data::String("row".into())), "spacing", Data::Number(5.0)); + let a = with(node("button", 1.0), "size", Data::Array(vec![Data::Number(100.0), Data::Number(20.0)])); + let b = with(node("button", 1.0), "size", Data::Array(vec![Data::Number(50.0), Data::Number(30.0)])); + let huge = + with(node("statictext", 0.0), "bounds", Data::Array(vec![Data::Number(-1e12), Data::Number(0.0), Data::Number(1e12), Data::Number(1e300)])); + let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog, row, a, b, huge])).unwrap(); + assert_eq!((d.nodes[1].rect.w, d.nodes[1].rect.h), (155.0, 30.0), "a row adds widths and spacing, and takes the tallest height"); + assert_eq!((d.nodes[2].rect.x, d.nodes[3].rect.x), (10.0, 115.0)); + assert_eq!(d.nodes[2].rect.y, 15.0, "a shorter control is centered in its row"); + for n in &d.nodes { + for v in [n.rect.x, n.rect.y, n.rect.w, n.rect.h] { + assert!(v.is_finite() && v.abs() <= MAX_EXTENT, "{:?}", n.rect); + } + } + let (w, h) = d.size(); + assert!(w <= MAX_EXTENT && h <= MAX_EXTENT); +} + +#[test] +fn characters_reserve_the_width_of_an_edit_field_or_a_static_text() { + let pair = |w: f64, h: f64| Data::Array(vec![Data::Number(w), Data::Number(h)]); + let text = |kind: &str, t: &str| with(node(kind, 0.0), "text", Data::String(t.into())); + let field = with(text("edittext", "Sample"), "characters", Data::Number(35.0)); + let plain = text("edittext", "Sample"); + let label = with(text("statictext", "Hi"), "characters", Data::Number(10.0)); + let sized = with(with(text("edittext", "Sample"), "characters", Data::Number(35.0)), "size", pair(100.0, 20.0)); + let dialog = with(node("dialog", -1.0), "orientation", Data::String("row".into())); + let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog, field, plain, label, sized])).unwrap(); + assert_eq!(d.nodes[1].rect.w, 35.0 * 7.0 + 12.0, "35 characters of room"); + assert_eq!(d.nodes[2].rect.w, 80.0, "without characters, the text's own width and the 80 minimum"); + assert_eq!(d.nodes[3].rect.w, 10.0 * 7.0 + 4.0); + assert_eq!(d.nodes[4].rect.w, 100.0, "a size set takes the place of the characters' width"); +} + +#[test] +fn a_hidden_control_and_what_it_holds_take_no_room() { + let dialog = with(node("dialog", -1.0), "orientation", Data::String("row".into())); + let pair = |w: f64, h: f64| Data::Array(vec![Data::Number(w), Data::Number(h)]); + let a = with(node("button", 0.0), "size", pair(100.0, 20.0)); + let hidden = with(node("group", 0.0), "visible", Data::Bool(false)); + let inside = with(node("button", 2.0), "size", pair(400.0, 300.0)); + let b = with(node("button", 0.0), "size", pair(50.0, 20.0)); + let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog.clone(), a.clone(), hidden, inside, b.clone()])).unwrap(); + let shown: ScriptUiDialog = scriptui::parse(&description(vec![dialog, a, b])).unwrap(); + assert_eq!(d.size(), shown.size(), "the hidden group and the button in it leave the dialog's size as it is"); + assert_eq!(d.nodes[4].rect.x, shown.nodes[2].rect.x, "the next control takes the hidden group's place"); + assert!(!d.nodes[3].visible, "the button in the hidden group is hidden too"); +} + +#[test] +fn a_control_s_size_keeps_within_its_minimum_and_maximum() { + let dialog = node("dialog", -1.0); + let pair = |w: f64, h: f64| Data::Array(vec![Data::Number(w), Data::Number(h)]); + let wide = with(with(node("button", 0.0), "size", pair(300.0, -1.0)), "max", pair(120.0, -1.0)); + let tall = with(with(node("button", 0.0), "size", pair(-1.0, -1.0)), "min", pair(-1.0, 60.0)); + let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog.clone(), wide, tall])).unwrap(); + assert_eq!(d.nodes[1].rect.w, 120.0, "the maximum width holds over a larger size"); + assert_eq!(d.nodes[2].rect.h, 60.0, "the minimum height holds over the estimate"); + let plain: ScriptUiDialog = scriptui::parse(&description(vec![dialog, node("button", 0.0)])).unwrap(); + assert!(plain.nodes[1].rect.h < 60.0 && plain.nodes[1].rect.w > 0.0, "a size of -1 leaves the side to the estimate"); + 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] +fn window_s_alert_confirm_and_prompt_open_the_script_dialogs() { + let mut s = one_doc(); + let answers = json!([{"kind": "alert", "value": "ok"}, {"kind": "confirm", "value": false}, {"kind": "prompt", "value": "typed"}]); + let r = headless(&mut s, "vc.log([typeof Window.alert('Hi'), Window.confirm('Go?'), Window.prompt('Name', 'x')]);", answers).unwrap(); + assert_eq!(r["log"], json!([["undefined", false, "typed"]]), "{r}"); + assert_eq!(r["dialogCount"], 3); +} + +/// A description of arbitrary kinds, containers in any order, numbers of any size (infinite and +/// not-a-number ones included) and texts of any length. +fn any_description() -> impl proptest::strategy::Strategy { + use proptest::prelude::*; + let kind = prop_oneof![ + Just("dialog"), + Just("group"), + Just("panel"), + Just("statictext"), + Just("edittext"), + Just("button"), + Just("checkbox"), + Just("radiobutton"), + Just("dropdownlist"), + Just("listbox"), + Just("slider"), + Just("progressbar"), + Just("wobble"), + ]; + let number = prop_oneof![1 => Just(f64::NAN), 1 => Just(f64::INFINITY), 1 => Just(-1e300), 1 => any::(), 6 => -50.0..400.0f64]; + let text = prop_oneof![2 => Just(String::new()), 8 => "[ -~]{0,40}", 1 => Just("x".repeat(MAX_TEXT_BYTES + 1))]; + let bounds = proptest::option::of(proptest::collection::vec(number.clone(), 4..=4)); + let size = proptest::option::of(proptest::collection::vec(number.clone(), 2..=2)); + // The container is a share of the controls before this one, or with a share past 1, one after it. + let fields = (kind, 0.0..1.1f64, text, bounds, size, 0..4usize, number); + proptest::collection::vec(fields, 0..40).prop_map(|nodes| { + let mut containers = vec![0usize]; + let mut out = Vec::new(); + for (i, (kind, share, text, bounds, size, items, value)) in nodes.into_iter().enumerate() { + let kind = if i == 0 { "dialog" } else { kind }; + let parent = match i { + 0 => -1.0, + _ if share >= 1.0 => (i + 1) as f64, + _ => containers[((share * containers.len() as f64) as usize).min(containers.len() - 1)] as f64, + }; + if matches!(kind, "group" | "panel") { + containers.push(i); + } + let numbers = |v: Option>| v.map_or(Data::Null, |v| Data::Array(v.into_iter().map(Data::Number).collect())); + let mut n = with(with(node(kind, parent), "text", Data::String(text)), "bounds", numbers(bounds)); + n = with(n, "size", numbers(size)); + n = with(n, "items", Data::Array((0..items).map(|k| Data::String(k.to_string())).collect())); + n = with(n, "selection", Data::Number(value)); + out.push(with(with(n, "minvalue", Data::Number(0.0)), "value", Data::Number(value))); + } + description(out) + }) +} + +proptest::proptest! { + #![proptest_config(proptest::prelude::ProptestConfig::with_cases(256))] + + /// Any description is refused with an error or laid out with every place and size finite and + /// within the limit. + #[test] + fn any_description_is_refused_or_laid_out_within_its_limits(d in any_description()) { + if let Ok(dialog) = scriptui::parse(&d) { + for n in &dialog.nodes { + for v in [n.rect.x, n.rect.y, n.rect.w, n.rect.h] { + proptest::prop_assert!(v.is_finite() && v.abs() <= MAX_EXTENT, "{:?}", n.rect); + } + proptest::prop_assert!(n.value.is_finite() && n.selection.is_none_or(|k| k < n.items.len())); + } + } + } +} + +#[test] +fn an_event_is_checked_against_the_dialog() { + let d = scriptui::parse(&description(vec![ + node("dialog", -1.0), + node("button", 0.0), + with(node("edittext", 0.0), "readonly", Data::Bool(true)), + with(with(with(node("slider", 0.0), "minvalue", Data::Number(0.0)), "maxvalue", Data::Number(10.0)), "value", Data::Number(4.0)), + with(node("listbox", 0.0), "items", Data::Array(vec![Data::String("a".into())])), + with(node("button", 0.0), "visible", Data::Bool(false)), + ])) + .unwrap(); + assert_eq!(scriptui::check_event(&d, UiEvent::Click(1)), Ok(UiEvent::Click(1))); + assert!(scriptui::check_event(&d, UiEvent::Click(0)).is_err(), "the dialog itself is no control"); + assert!(scriptui::check_event(&d, UiEvent::Change(2, UiValue::Text("x".into()))).is_err(), "a read-only field takes no text"); + assert_eq!(scriptui::check_event(&d, UiEvent::Change(3, UiValue::Number(-5.0))), Ok(UiEvent::Change(3, UiValue::Number(0.0)))); + assert!(scriptui::check_event(&d, UiEvent::Change(3, UiValue::Number(f64::NAN))).is_err()); + assert!(scriptui::check_event(&d, UiEvent::Change(4, UiValue::Index(Some(1)))).is_err()); + assert_eq!(scriptui::check_event(&d, UiEvent::Change(4, UiValue::Index(None))), Ok(UiEvent::Change(4, UiValue::Index(None)))); + assert!(scriptui::check_event(&d, UiEvent::Click(5)).is_err(), "a hidden control takes no events"); + assert_eq!(scriptui::check_event(&d, UiEvent::Close), Ok(UiEvent::Close)); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index b7257d62b1..313b2aad20 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -42,11 +42,13 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ]; /// The names the host adds that stay inside the document and the run, by the object that has them. -/// Reading a file or a folder, a file dialog and a message to the person do not change anything -/// outside it. The document model (`app`, its classes and the enumerations) acts on the open -/// documents; `Document.saveAs` and `close` throw "not available yet". +/// Reading a file or a folder, a file dialog, a message to the person and a ScriptUI dialog do not +/// change anything outside it. The document model (`app`, its classes and the enumerations) acts on +/// the open documents; `Document.saveAs` and `close` throw "not available yet". const INSIDE: &[(&str, &str)] = &[ - ("", "$ File Folder UnitValue alert confirm localize prompt toSource"), + ("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"), + ("Window.", "alert confirm length prompt prototype"), + ("Window.prototype.", "add addEventListener center close constructor findElement hide remove removeEventListener show"), ("Object.prototype.", "reflect toSource"), ("UnitValue.", "baseUnit baseUnit= length prototype"), ("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="), diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index fd32b00549..df5829a41b 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -659,6 +659,7 @@ fn ask_pick(i: &mut Interp, kind: &'static str, me: Option<&Value>, prompt: &Val args: vec![Value::str(kind), prompt, Value::Bool(multi), start, types], keep: vec![Value::Bool(kind == "folder"), me.cloned().unwrap_or(Value::Null), filter.clone()], resume: picked, + failed: None, }) } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 3d2e63ceeb..89821e7734 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -243,18 +243,25 @@ pub(crate) type CodeObserver = Rc; pub(crate) type PausableFn = fn(&mut Interp, Value, &[Value]) -> JsResult; /// What a [`PausableFn`] does with the host's answer: it is given the values it kept and the -/// answer, and gives the result of its call. +/// answer, and gives the result of its call. One that puts another [`Pause`] in +/// [`Interp::again`] makes that host call next, and the call's result is what that pause's +/// resume function gives. pub(crate) type ResumeFn = fn(&mut Interp, &[Value], Value) -> JsResult; +/// What a [`Pause`] does with its kept values when its host call fails. +pub(crate) type FailFn = fn(&mut Interp, &[Value]); + /// The host call a [`PausableFn`] makes: the host function `host` with `args`. Its answer goes to /// `resume` with `keep`, at once when the host answers at once. When the host waits /// ([`crate::HostError::Wait`]), the run pauses at the call, and `resume` runs when the run goes on /// after [`crate::Realm::answer`]; a run ended while it waits ([`crate::Realm::end`]) drops it. +/// When the host call fails, `failed` is given `keep` before the error is thrown at the call. pub(crate) struct Pause { pub(crate) host: Value, pub(crate) args: Vec, pub(crate) keep: Vec, pub(crate) resume: ResumeFn, + pub(crate) failed: Option, } /// A [`Pause`] whose host call waits for its answer. @@ -369,6 +376,10 @@ pub(crate) struct Interp { /// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before /// the next instruction runs. pub(crate) resuming: Option, + /// The next host call a resume function asks for ([`ResumeFn`]). + pub(crate) again: Option, + /// ScriptUI's `Window` and its controls, when the host added them. + pub(crate) script_ui: Option, /// The message of the uncatchable error a host function ended the run with. pub(crate) host_abort: Option, /// How much a value passed to or from a host function may carry. @@ -671,6 +682,8 @@ impl Interp { waiting_hosted: false, constructing: false, resuming: None, + again: None, + script_ui: None, host_abort: None, data_limits: crate::DataLimits::default(), source_tag: crate::realm::UNKNOWN_SOURCE, @@ -919,6 +932,7 @@ impl Interp { roots.values.extend(self.stack.iter()); roots.values.extend(self.temp_roots.iter()); roots.values.extend(self.resuming.iter().flat_map(|r| r.keep.iter())); + roots.values.extend(self.again.iter().flat_map(|p| p.keep.iter().chain(p.args.iter()).chain(std::iter::once(&p.host)))); roots.values.push(&self.last_thrown); roots.values.push(&self.last_error); roots.values.push(&self.passing); @@ -937,6 +951,7 @@ impl Interp { roots.objects.push(self.global); roots.objects.extend(self.intrinsics.all()); roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); + roots.objects.extend(self.script_ui.iter().flat_map(crate::scriptui::Classes::objects)); roots.objects.extend(self.xmp.iter().flat_map(crate::xmp_classes::Classes::objects)); roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects)); roots.values.extend(self.symbols.root_values()); @@ -3378,35 +3393,64 @@ impl Interp { /// Makes the host call a [`PausableFn`] gave, whose answer goes to its resume function. A host /// function is called as the script's own code calls it, so it may wait; then the resume /// function is kept for the answer [`crate::Realm::answer`] gives, and the value that stands - /// in for that answer is the call's result for now. + /// in for that answer is the call's result for now. A resume function that asks [`Self::again`] + /// makes that call next, in this loop, so a built-in may ask any number of times. fn ask(&mut self, p: Pause) -> JsResult { - let Pause { host, args, keep, resume } = p; - let mark = self.temp_roots.len(); - self.temp_roots.push(host.clone()); - self.temp_roots.extend(args.iter().cloned()); - self.temp_roots.extend(keep.iter().cloned()); - let was_waiting = self.waiting; - let answer = match self.func_of(&host) { - Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &Value::Undefined, &args, &read), - _ => self.call(&host, &Value::Undefined, &args), - }; - self.temp_roots.truncate(mark); - let answer = answer?; - let r = Resumption { resume, keep }; - if self.waiting && !was_waiting { - self.resuming = Some(r); - return Ok(answer); + let mut p = p; + loop { + let Pause { host, args, keep, resume, failed } = p; + let mark = self.temp_roots.len(); + self.temp_roots.push(host.clone()); + self.temp_roots.extend(args.iter().cloned()); + self.temp_roots.extend(keep.iter().cloned()); + let was_waiting = self.waiting; + let answer = match self.func_of(&host) { + Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &Value::Undefined, &args, &read), + _ => self.call(&host, &Value::Undefined, &args), + }; + if let Err(e) = &answer + && let Some(failed) = failed + { + // The thrown value stays kept from collection while `failed` runs. + if let Abrupt::Throw(v) = e { + self.temp_roots.push(v.clone()); + } + failed(self, &keep); + } + self.temp_roots.truncate(mark); + let answer = answer?; + let r = Resumption { resume, keep }; + if self.waiting && !was_waiting { + self.resuming = Some(r); + return Ok(answer); + } + let v = self.resume_once(r, answer)?; + match self.again.take() { + Some(next) => p = next, + None => return Ok(v), + } } - self.resume(r, answer) } - /// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function. + /// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function, and + /// makes the host call it asks for next, if any. fn resume(&mut self, r: Resumption, answer: Value) -> JsResult { + let v = self.resume_once(r, answer)?; + match self.again.take() { + Some(next) => self.ask(next), + None => Ok(v), + } + } + + fn resume_once(&mut self, r: Resumption, answer: Value) -> JsResult { let mark = self.temp_roots.len(); self.temp_roots.push(answer.clone()); self.temp_roots.extend(r.keep.iter().cloned()); let v = (r.resume)(self, &r.keep, answer); self.temp_roots.truncate(mark); + if v.is_err() { + self.again = None; + } v } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 39e8e541b3..0db46fc6a6 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -134,6 +134,8 @@ mod reflect; mod regexp; mod regexp_builtins; mod regexp_vm; +pub mod scriptui; +mod scriptui_resource; mod string_builtins; mod symbol; mod token; @@ -316,6 +318,8 @@ mod promise_tests; #[cfg(test)] mod reflect_tests; #[cfg(test)] +mod scriptui_tests; +#[cfg(test)] mod symbol_tests; #[cfg(test)] mod tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index cd69a31454..4ecc24846f 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -305,6 +305,8 @@ impl Realm { interp.waiting_hosted = false; interp.constructing = false; interp.resuming = None; + interp.again = None; + crate::scriptui::end_run(interp); interp.error_tag = UNKNOWN_SOURCE; interp.thrown_mark = None; interp.finally_marks.clear(); @@ -363,6 +365,8 @@ impl Realm { interp.waiting_hosted = false; interp.constructing = false; interp.resuming = None; + interp.again = None; + crate::scriptui::end_run(interp); interp.passing = Value::Undefined; interp.end_jobs(result.is_ok()); if let Some(es2015) = interp.next_es2015.take() { @@ -601,6 +605,19 @@ impl Realm { } } + /// Adds ScriptUI's global constructor `Window` ([`crate::scriptui`]), whose dialogs the host + /// functions in `items` show: `open` and `wait`, each given the dialog's description, and + /// `end`, given the result of `show()` and whether `show()` ended normally. A run that ends + /// while `show()` waits for `wait`'s answer, because it is stopped or the host does not resume + /// it, ends without a call to `end`: the host releases what it holds for the dialog when the run + /// ends, and does not wait for `end`. + pub fn define_script_ui(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> { + match crate::scriptui::install(&mut self.interp, items) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Adds the global constructors `File` and `Folder`, whose file system work the host functions /// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`, /// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`, diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs new file mode 100644 index 0000000000..47d8aeaffb --- /dev/null +++ b/crates/js/src/scriptui.rs @@ -0,0 +1,2116 @@ +//! ScriptUI's `Window` with modal dialogs, as the help page +//! describes it, whose +//! drawing a host does ([`crate::Realm::define_script_ui`]). +//! +//! `new Window("dialog"[, title, bounds, properties])` makes a dialog, with or without `new`. A +//! window of type `palette` or `window` throws an `Error` that says it is not available yet. +//! `new Window` and `add` also take a resource specification in place of the type, as the help +//! page +//! describes it (read by [`crate::scriptui_resource`]), and then read no other argument: the +//! window or control is made with the creation properties given in `properties`. Then, in order, +//! each control listed in its braces is added to it through `add`, with `add`'s limits, and +//! assigned to the container's property of that name, a list's `items` gives its item texts as +//! `add`'s third argument does, and each other value is assigned to the property of its name. A +//! malformed specification throws a `SyntaxError`. `add(type[, bounds, text, properties])` adds a +//! control to a dialog, a `group` or a `panel` and returns it: `statictext`, `edittext`, `button`, +//! `checkbox`, `radiobutton`, `dropdownlist`, `listbox` (whose third argument is an array of item +//! texts), `slider` (third to fifth: value, minimum, maximum) and `progressbar` (value, maximum). +//! The other documented control types throw an `Error` that says they are not available yet, and +//! `show()` throws one for an `edittext` whose `properties` have `noecho`. A +//! group takes its creation properties as the third argument (or the fourth when the third is not +//! an object), and a list takes them there in place of its items, with the items in +//! `properties.items`. A list's `add("item", text)` adds an item, `find(text)` finds one and +//! `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: 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 +//! does. +//! +//! `addEventListener(type, handler[, capture])` and `removeEventListener` register handlers for +//! 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()`. 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. +//! +//! `show()` gives the host's `open` the dialog's description and runs `onShow`. Then, until the +//! dialog closes, it gives the host's `wait` the description again, and `wait` gives back what the +//! person did, which may pause the run ([`crate::interp::Pause`]): a `click` on a control, a +//! `change` with its new value, or a `close`. The control takes the change, its `onClick`, +//! `onChanging` or `onChange` runs, and the next description shows what the handler changed. A +//! button without `onClick` 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 and [`MAX_LISTENERS`] are +//! VectorCraft's own limits. A getter that changes a list's items or an item's text after the list +//! was read, or adds or removes a control after the dialog's controls were read, makes `show()` +//! read the dialog again, and a dialog that changes again throws an `Error`. A `text` getter +//! that changes a list or a container while `remove(text)` looks for an item or a control makes +//! `remove` throw an `Error`. + +use crate::HostItem; +use crate::builtins::{arg, constructor, data, method, native, pausable_method}; +use crate::heap::{Class, ENUMERABLE, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key, string_bytes}; +use crate::host::Data; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult, Pause}; +use crate::scriptui_resource::{self, Fault, Res, Spec}; +use crate::value::{Value, index_key}; + +/// The most controls a dialog holds, its groups and panels included. +pub const MAX_CONTROLS: usize = 512; +/// How deeply controls nest in a dialog: a control the dialog holds is at depth 1. +pub const MAX_DEPTH: usize = 16; +/// The most items a dialog's lists hold together. +pub const MAX_ITEMS: usize = 1024; +/// The most bytes (UTF-8) of one text in a dialog: a control's text or name, or a list item's. +pub const MAX_TEXT_BYTES: usize = 16 << 10; +/// The most event listeners one window or control holds. +pub const MAX_LISTENERS: usize = 256; + +/// The control types `add` makes. +pub const BUILT: [&str; 11] = + ["group", "panel", "statictext", "edittext", "button", "checkbox", "radiobutton", "dropdownlist", "listbox", "slider", "progressbar"]; +/// The documented control types that are not available yet. +const LATER: [&str; 10] = + ["tabbedpanel", "tab", "scrollbar", "image", "iconbutton", "treeview", "flashplayer", "customview", "custombutton", "customboundedvalue"]; + +const KIND: &str = "__vcKind"; +const PARENT: &str = "__vcParent"; +const WINDOW: &str = "__vcWindow"; +const KIDS: &str = "__vcKids"; +const DEPTH: &str = "__vcDepth"; +const COUNT: &str = "__vcCount"; +const ITEM_COUNT: &str = "__vcItemCount"; +const CLOSING: &str = "__vcClosing"; +const ITEMS: &str = "__vcItems"; +/// How many times a list's items have been replaced, which tells a list from one whose items were +/// removed and added again with the same texts. +const ITEMS_REV: &str = "__vcItemsRev"; +const SELECTION: &str = "__vcSelection"; +const LIST: &str = "__vcList"; +const VALUE: &str = "__vcValue"; +const LISTENERS: &str = "__vcListeners"; +const STOPPED: &str = "__vcStopped"; +const ID: &str = "__vcId"; +/// The number of listeners an element has had registered, which numbers each registration. +const REGISTERED: &str = "__vcRegistered"; + +/// The longest array an element keeps in a slot: a list's items, a container's controls, its +/// listeners (four values each), and the elements of a description. +const LIST_CAP: u32 = { + let most = if MAX_ITEMS > MAX_CONTROLS + 1 { MAX_ITEMS } else { MAX_CONTROLS + 1 }; + let most = if most > 4 * MAX_LISTENERS { most } else { 4 * 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"]; +/// The events `addEventListener` takes, which `show()` and `notify` run. +const EVENTS: [&str; 4] = ["click", "change", "changing", "show"]; +/// The other documented events, which nothing runs yet. +const EVENTS_LATER: [&str; 14] = [ + "move", + "moving", + "resize", + "resizing", + "enterKey", + "focus", + "blur", + "mousedown", + "mouseup", + "mousemove", + "mouseover", + "mouseout", + "keyup", + "keydown", +]; + +/// The objects of `Window`, kept by the realm, and the dialog that is showing. +#[derive(Clone, Debug)] +pub(crate) struct Classes { + window_proto: ObjId, + control_proto: ObjId, + item_proto: ObjId, + event_proto: ObjId, + layout: ObjId, + host: ObjId, + selection_get: ObjId, + selection_set: ObjId, + radio_get: ObjId, + radio_set: ObjId, + showing: Option, + /// 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 { + /// The objects a collection keeps. + pub(crate) fn objects(&self) -> Vec { + let mut all = vec![ + self.window_proto, + self.control_proto, + self.item_proto, + self.event_proto, + self.layout, + self.host, + self.selection_get, + self.selection_set, + self.radio_get, + self.radio_set, + ]; + all.extend(self.showing); + all.extend(self.dispatching.iter().copied()); + all.extend(self.above.iter().copied()); + all + } +} + +/// 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(); + c.above.clear(); + } +} + +fn classes(i: &Interp) -> JsResult { + i.script_ui.clone().ok_or_else(|| Abrupt::Internal("Window is not installed".into())) +} + +fn error(i: &mut Interp, message: &str) -> Abrupt { + i.throw(ErrorType::Error, message) +} + +fn range(i: &mut Interp, message: &str) -> Abrupt { + i.throw(ErrorType::Range, message) +} + +/// The value of the own data property `name` of `o`, `undefined` when it has none. +fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { + Ok(match i.get_own_property(o, &key(name))? { + Some(Prop::Data { value, .. }) => value, + _ => Value::Undefined, + }) +} + +/// Sets the property `name` of `o` that a script can read but not change. +fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { + i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES))?; + i.define(o, key(name), Prop::Data { value, flags: 0 }) +} + +/// Gives the list `o` the array `kept` as its items and counts the replacement ([`ITEMS_REV`]). +fn set_items(i: &mut Interp, o: ObjId, kept: ObjId) -> JsResult<()> { + let rev = number_slot(i, o, ITEMS_REV)? + 1.0; + // The array stays kept from collection while the revision's slot reserves room. + i.rooted(&[Value::Object(kept)], |i| set_slot(i, o, ITEMS_REV, Value::Number(rev)))?; + set_slot(i, o, ITEMS, Value::Object(kept)) +} + +/// The writes that give the list `o` the array `kept` as its items and `copy` as the array a script +/// can change, counting the replacement ([`ITEMS_REV`]), for [`write_all`]. +fn item_writes(i: &Interp, o: ObjId, kept: Value, copy: Value) -> JsResult<[Write<'static>; 3]> { + let rev = number_slot(i, o, ITEMS_REV)? + 1.0; + Ok([(o, ITEMS_REV, Value::Number(rev), 0), (o, ITEMS, kept, 0), (o, "items", copy, OPEN)]) +} + +/// Sets the property `name` of `o` that a script can change. +fn set_open(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { + i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES))?; + i.define(o, key(name), Prop::Data { value, flags: OPEN }) +} + +fn number_slot(i: &Interp, o: ObjId, name: &str) -> JsResult { + Ok(match slot(i, o, name)? { + Value::Number(n) => n, + _ => 0.0, + }) +} + +fn object_slot(i: &Interp, o: ObjId, name: &str) -> JsResult> { + Ok(slot(i, o, name)?.as_object()) +} + +/// An element's kind, or `None` for a value that is not a ScriptUI window or control. +fn kind_of(i: &Interp, v: &Value) -> JsResult> { + let Some(o) = v.as_object() else { return Ok(None) }; + Ok(match slot(i, o, KIND)? { + Value::String(s) => Some((o, s.to_rust_string())), + _ => None, + }) +} + +/// `this` as an element, or a `TypeError` naming `what`. +fn element(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, String)> { + match kind_of(i, this)? { + Some(e) => Ok(e), + None => Err(i.type_error(&format!("{what}: this is not a ScriptUI window or control"))), + } +} + +/// 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"))), + } +} + +/// [`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`]. 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, .. } if *length <= LIST_CAP => *length, + _ => return Ok(Vec::new()), + }; + (0..length) + .map(|n| { + Ok(match i.get_own_property(a, &index_key(n))? { + Some(Prop::Data { value, .. }) => value, + _ => Value::Undefined, + }) + }) + .collect() +} + +/// A new array holding `items`: one a script cannot change unless `open`. +fn list(i: &mut Interp, items: &[Value], open: bool) -> JsResult { + i.rooted(items, |i| i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(items.len() + 1))))?; + let proto = i.intrinsics.array_proto; + let a = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: open }, Some(proto))); + let flags = if open { OPEN } else { ENUMERABLE }; + for (n, v) in items.iter().enumerate() { + let n = u32::try_from(n).map_err(|_| Abrupt::Internal("a list is too long".into()))?; + i.define(a, index_key(n), Prop::Data { value: v.clone(), flags })?; + } + i.object_mut(a)?.extensible = open; + Ok(a) +} + +/// A write of `value` to the property of an object with a name and flags, made by [`write_all`]. +type Write<'a> = (ObjId, &'a str, Value, u8); + +/// Makes `writes` in order, after checking once that the heap has room for the properties they +/// add, so a run that ends here (out of memory) makes none of them. +fn write_all(i: &mut Interp, writes: Vec>) -> JsResult<()> { + let values: Vec = writes.iter().map(|(_, _, v, _)| v.clone()).collect(); + i.rooted(&values, |i| { + // The heap grows only by the properties a write adds. + let mut growth = 0; + for (at, name, _, _) in &writes { + if !i.object(*at)?.props.contains(&key(name)) { + growth += PROP_BYTES + string_bytes(name.len()); + } + } + i.reserve_heap(growth)?; + for (at, name, value, flags) in writes { + i.define(at, key(name), Prop::Data { value, flags })?; + } + Ok(()) + }) +} + +/// Adds `v` to the end of the list in `o`'s slot `name`, puts a copy a script can change in its +/// property `public`, and makes the writes in `more` with them. Both arrays are made before the +/// first write, so a run that ends here leaves the lists and `more`'s properties as they were. +fn append<'a>(i: &mut Interp, o: ObjId, name: &'a str, public: &'a str, v: Value, more: Vec>) -> JsResult<()> { + let mut items = match object_slot(i, o, name)? { + Some(a) => list_values(i, a)?, + None => Vec::new(), + }; + items.push(v); + i.rooted(&items.clone(), |i| { + let kept = Value::Object(list(i, &items, false)?); + i.rooted(std::slice::from_ref(&kept), |i| { + let copy = Value::Object(list(i, &items, true)?); + let mut writes = vec![(o, name, kept.clone(), 0), (o, public, copy, OPEN)]; + writes.extend(more); + write_all(i, writes) + }) + }) +} + +fn text_arg(i: &mut Interp, v: &Value) -> JsResult { + Ok(match v { + Value::Undefined => Value::str(""), + v => Value::String(i.to_str(v)?), + }) +} + +/// A new element of `kind`, with the properties every element has. +fn new_element( + i: &mut Interp, + proto: ObjId, + kind: &str, + parent: Option, + window: Option, + depth: usize, + args: [&Value; 3], +) -> JsResult { + let [bounds, text, props] = args; + i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(32)))?; + let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + i.temp_roots.push(Value::Object(o)); + let window = window.unwrap_or(o); + let parent = parent.map_or(Value::Null, Value::Object); + let layout = classes(i)?.layout; + set_slot(i, o, KIND, Value::str(kind))?; + set_slot(i, o, PARENT, parent.clone())?; + set_slot(i, o, WINDOW, Value::Object(window))?; + set_slot(i, o, DEPTH, Value::Number(depth as f64))?; + 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))?; + let text = text_arg(i, text)?; + set_open(i, o, "text", text)?; + let props = match props { + Value::Object(_) => props.clone(), + _ => Value::Object(i.new_object()), + }; + set_open(i, o, "properties", props.clone())?; + let name = i.get_value(&props, &key("name"))?; + let name = text_arg(i, &name)?; + set_open(i, o, "name", name)?; + set_open(i, o, "enabled", Value::Bool(true))?; + set_open(i, o, "visible", Value::Bool(true))?; + if !matches!(bounds, Value::Undefined | Value::Null) { + set_open(i, o, "bounds", bounds.clone())?; + } + set_open(i, o, "layout", Value::Object(layout))?; + for name in SIZES { + let d = dimension(i, -1.0, -1.0)?; + set_open(i, o, name, d)?; + } + let container = matches!(kind, "dialog" | "group" | "panel"); + if container { + let kids = list(i, &[], false)?; + set_slot(i, o, KIDS, Value::Object(kids))?; + let children = list(i, &[], true)?; + set_open(i, o, "children", Value::Object(children))?; + set_open(i, o, "orientation", Value::str(if kind == "group" { "row" } else { "column" }))?; + set_open(i, o, "alignChildren", Value::str("center"))?; + set_open(i, o, "spacing", Value::Number(10.0))?; + set_open(i, o, "margins", Value::Number(if kind == "group" { 0.0 } else { 15.0 }))?; + } + // Layout properties given with the creation properties start the element with those values. + let layout_names: &[&str] = if container { &["alignment", "orientation", "alignChildren", "spacing", "margins"] } else { &["alignment"] }; + for name in layout_names { + let v = i.get_value(&props, &key(name))?; + if !matches!(v, Value::Undefined) { + set_open(i, o, name, v)?; + } + } + Ok(o) +} + +/// A new size object with `width` and `height`. +fn dimension(i: &mut Interp, width: f64, height: f64) -> JsResult { + i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(2)))?; + let o = i.new_object(); + i.rooted(&[Value::Object(o)], |i| { + set_open(i, o, "width", Value::Number(width))?; + set_open(i, o, "height", Value::Number(height))?; + Ok(Value::Object(o)) + }) +} + +/// `new Window(type[, title, bounds, properties])`. +fn window_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let kind = i.to_str(&arg(args, 0))?.to_rust_string(); + let spec = if is_resource(&kind) { Some(resource(i, &kind, "Window")?) } else { None }; + let lower = spec.as_ref().map_or(kind.as_str(), |s| s.class.as_str()).to_lowercase(); + if lower == "palette" || lower == "window" { + return Err(error(i, &format!("Window: a window of type {lower} is not available yet; use dialog"))); + } + if lower != "dialog" { + return Err(error(i, "Window: the type must be dialog, palette or window")); + } + let proto = classes(i)?.window_proto; + let mark = i.temp_roots.len(); + let r = (|| { + // A resource specification gives everything; the other arguments are not read. + let o = match &spec { + Some(spec) => { + let creation = creation_properties(i, spec)?; + new_element(i, proto, "dialog", None, None, 0, [&Value::Undefined, &Value::Undefined, &creation])? + } + None => new_element(i, proto, "dialog", None, None, 0, [&arg(args, 2), &arg(args, 1), &arg(args, 3)])?, + }; + set_slot(i, o, COUNT, Value::Number(0.0))?; + set_slot(i, o, ITEM_COUNT, Value::Number(0.0))?; + if let Some(spec) = &spec { + apply_resource(i, o, spec, false)?; + } + Ok(Value::Object(o)) + })(); + i.temp_roots.truncate(mark); + r +} + +/// Is the type `text` a resource specification: a type with braces, or a name before a `:`? A type +/// name alone is not. +fn is_resource(text: &str) -> bool { + text.contains('{') || text.contains(':') +} + +/// The resource specification `text` given to `what`, or a `SyntaxError` or `RangeError` naming +/// `what`. +fn resource(i: &mut Interp, text: &str, what: &str) -> JsResult { + match scriptui_resource::parse(text) { + Ok(spec) => Ok(spec), + Err(Fault::Syntax(m)) => Err(i.throw(ErrorType::Syntax, &format!("{what}: {m}"))), + Err(Fault::Limit(m)) => Err(range(i, &format!("{what}: {m}"))), + } +} + +/// The value of a resource specification's `properties`, its creation properties, kept in the +/// temporary roots; `undefined` when it has none. +fn creation_properties(i: &mut Interp, spec: &Spec) -> JsResult { + let Some((_, v)) = spec.props.iter().rev().find(|(name, _)| name == "properties") else { return Ok(Value::Undefined) }; + if matches!(v, Res::Control(_)) { + return Err(i.type_error("properties: give the creation properties as an object")); + } + let v = resource_value(i, v)?; + i.temp_roots.push(v.clone()); + Ok(v) +} + +/// A new value for the resource value `v`, built in the temporary roots. +fn resource_value(i: &mut Interp, v: &Res) -> JsResult { + Ok(match v { + Res::Null => Value::Null, + Res::Bool(b) => Value::Bool(*b), + Res::Number(n) => Value::Number(*n), + Res::String(s) => Value::str(s), + Res::Array(items) => { + let mut values = Vec::with_capacity(items.len()); + for item in items { + let v = resource_value(i, item)?; + i.temp_roots.push(v.clone()); + values.push(v); + } + let a = list(i, &values, true)?; + i.temp_roots.push(Value::Object(a)); + Value::Object(a) + } + Res::Object(props) => { + i.reserve_heap(OBJECT_BYTES)?; + let o = i.new_object(); + i.temp_roots.push(Value::Object(o)); + for (name, v) in props { + let v = resource_value(i, v)?; + set_open(i, o, name, v)?; + } + Value::Object(o) + } + Res::Control(_) => return Err(i.type_error("a control is not a value")), + }) +} + +/// Adds the control `spec` describes to the container `parent`, as `add` does, with the controls +/// and properties it lists. +fn add_resource(i: &mut Interp, parent: ObjId, spec: &Spec) -> JsResult { + let creation = creation_properties(i, spec)?; + // `add` reads a slider's and a progress bar's later arguments as numbers; their creation + // properties are set after `add` makes them. + let class = spec.class.to_lowercase(); + let numeric = matches!(class.as_str(), "slider" | "progressbar"); + // A list's `items` gives its item texts, as `add`'s third argument does. + let list_kind = matches!(class.as_str(), "dropdownlist" | "listbox"); + let items = match spec.props.iter().rev().find(|(name, _)| name == "items") { + // Only an array is item texts; `add` would read an object third as creation properties. + Some((_, Res::Null)) if list_kind => Value::Undefined, + Some((_, v)) if list_kind && !matches!(v, Res::Array(_)) => { + return Err(i.type_error("items: give a list's items as an array")); + } + Some((_, v)) if list_kind => { + let v = resource_value(i, v)?; + i.temp_roots.push(v.clone()); + v + } + _ => Value::Undefined, + }; + let args = if numeric { vec![Value::str(&spec.class)] } else { vec![Value::str(&spec.class), Value::Undefined, items, creation.clone()] }; + let c = add(i, Value::Object(parent), &args, false)?; + i.temp_roots.push(c.clone()); + let Some(o) = c.as_object() else { return Err(Abrupt::Internal("add gave no control".into())) }; + if numeric && creation.as_object().is_some() { + set_open(i, o, "properties", creation.clone())?; + let name = i.get_value(&creation, &key("name"))?; + let name = text_arg(i, &name)?; + set_open(i, o, "name", name)?; + let alignment = i.get_value(&creation, &key("alignment"))?; + if !matches!(alignment, Value::Undefined) { + set_open(i, o, "alignment", alignment)?; + } + } + apply_resource(i, o, spec, list_kind)?; + Ok(c) +} + +/// Sets the properties `spec` lists on the element `o`, in order, leaving out `properties`, and +/// `items` for a list (`list`): a control is added to `o` and assigned to `o`'s property of that +/// name, and any other value is assigned to the property of its name. +fn apply_resource(i: &mut Interp, o: ObjId, spec: &Spec, list: bool) -> JsResult<()> { + for (name, v) in &spec.props { + if name == "properties" || (list && name == "items") { + continue; + } + let value = match v { + Res::Control(child) => add_resource(i, o, child)?, + v => resource_value(i, v)?, + }; + i.temp_roots.push(value.clone()); + i.put(o, key(name), value, true)?; + } + Ok(()) +} + +fn number_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let n = i.to_number(v)?; + if !n.is_finite() { + return Err(range(i, &format!("{what} is not a finite number"))); + } + Ok(n) +} + +/// `container.add(type[, bounds, text, properties])` and `list.add("item", text)`. +fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, kind) = element(i, &this, "add")?; + 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" { + return Err(error(i, "add: a list holds only items")); + } + return add_item(i, o, &arg(args, 1)); + } + if !matches!(kind.as_str(), "dialog" | "group" | "panel") { + return Err(error(i, &format!("add: a {kind} holds no controls"))); + } + if is_resource(&ty) { + let spec = resource(i, &ty, "add")?; + let mark = i.temp_roots.len(); + let r = add_resource(i, o, &spec); + i.temp_roots.truncate(mark); + return r; + } + let ty = ty.to_lowercase(); + if LATER.contains(&ty.as_str()) { + return Err(error(i, &format!("add: the control type {ty} is not available yet"))); + } + let Some(&ty) = BUILT.iter().find(|b| **b == ty) else { return Err(error(i, &format!("add: there is no control type {ty}"))) }; + let depth = number_slot(i, o, DEPTH)? as usize + 1; + if depth > MAX_DEPTH { + return Err(range(i, &format!("add: controls can be nested at most {MAX_DEPTH} deep"))); + } + let 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"))); + } + let list_kind = ty == "dropdownlist" || ty == "listbox"; + let third = arg(args, 2); + let is_array = |i: &Interp, v: &Value| -> JsResult { + Ok(match v.as_object() { + Some(a) => matches!(i.object(a)?.class, Class::Array { .. }), + None => false, + }) + }; + // A group takes its creation properties third, and so may a list in place of its items; 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(); + let r = (|| { + let mut given_items = if list_kind && !props_third { third.clone() } else { Value::Undefined }; + if list_kind && props.as_object().is_some() { + let listed = i.get_value(&props, &key("items"))?; + i.temp_roots.push(listed.clone()); + if !matches!(listed, Value::Undefined | Value::Null) { + if !matches!(given_items, Value::Undefined | Value::Null) { + return Err(i.type_error("add: give a list's items as the third argument or in properties.items, not both")); + } + given_items = listed; + } + } + if ty == "listbox" && props.as_object().is_some() && i.get_value(&props, &key("multiselect"))?.truthy() { + return Err(error(i, "add: a list box that selects several items is not available yet")); + } + let creation = if matches!(ty, "slider" | "progressbar") { Value::Undefined } else { props.clone() }; + let text = if list_kind || matches!(ty, "group" | "slider" | "progressbar") { Value::Undefined } else { third.clone() }; + let c = new_element(i, proto, ty, Some(o), Some(win), depth, [&arg(args, 1), &text, &creation])?; + match ty { + "checkbox" => set_open(i, c, "value", Value::Bool(false))?, + "radiobutton" => { + set_slot(i, c, VALUE, Value::Bool(false))?; + let cl = classes(i)?; + i.define(c, key("value"), Prop::Accessor { get: Some(cl.radio_get), set: Some(cl.radio_set), flags: ENUMERABLE })?; + } + "slider" | "progressbar" => { + let (value, min, max) = + if ty == "slider" { (arg(args, 2), arg(args, 3), arg(args, 4)) } else { (arg(args, 2), Value::Undefined, arg(args, 3)) }; + let given = |v: &Value| !matches!(v, Value::Undefined); + let value = if given(&value) { number_arg(i, &value, "add: the value")? } else { 0.0 }; + let min = if given(&min) { number_arg(i, &min, "add: the minimum value")? } else { 0.0 }; + let max = if given(&max) { number_arg(i, &max, "add: the maximum value")? } else { 100.0 }; + set_open(i, c, "minvalue", Value::Number(min))?; + set_open(i, c, "maxvalue", Value::Number(max))?; + set_open(i, c, "value", Value::Number(value))?; + } + "dropdownlist" | "listbox" => { + let kept = list(i, &[], false)?; + set_items(i, c, kept)?; + set_slot(i, c, SELECTION, Value::Number(-1.0))?; + let items = list(i, &[], true)?; + set_open(i, c, "items", Value::Object(items))?; + let cl = classes(i)?; + i.define(c, key("selection"), Prop::Accessor { get: Some(cl.selection_get), set: Some(cl.selection_set), flags: ENUMERABLE })?; + } + _ => {} + } + // A new list's items take their places in the dialog only once the list is added. + let mut staged = 0usize; + if list_kind { + match given_items.clone() { + Value::Undefined | Value::Null => {} + Value::Object(a) if matches!(i.object(a)?.class, Class::Array { .. }) => { + let length = match &i.object(a)?.class { + Class::Array { length, .. } => *length as usize, + _ => 0, + }; + if length > MAX_ITEMS.saturating_sub(number_slot(i, win, ITEM_COUNT)? as usize) { + return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + // Each item is read as a script reads it, so an index getter gives its value. + let mut texts = Vec::with_capacity(length); + for n in 0..length { + let n = u32::try_from(n).map_err(|_| Abrupt::Internal("a list is too long".into()))?; + let item = i.get_value(&Value::Object(a), &index_key(n))?; + i.temp_roots.push(item.clone()); + let text = text_arg(i, &item)?; + i.temp_roots.push(text.clone()); + texts.push(text); + } + staged = new_items(i, c, &texts)?; + } + _ => return Err(i.type_error("add: give a list's items as an array")), + } + } + // A getter or a conversion above may have added controls or items itself, or removed the + // container from its dialog. An object made to look like a container is not in the dialog, + // so it charges nothing to the dialog's controls. + window_in(i, o, "add")?; + let count = number_slot(i, win, COUNT)?; + if count as usize >= MAX_CONTROLS { + return Err(range(i, &format!("add: a dialog can hold at most {MAX_CONTROLS} controls"))); + } + let items = number_slot(i, win, ITEM_COUNT)?; + if items as usize + staged > MAX_ITEMS { + return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + let counts = vec![(win, COUNT, Value::Number(count + 1.0), 0), (win, ITEM_COUNT, Value::Number(items + staged as f64), 0)]; + append(i, o, KIDS, "children", Value::Object(c), counts)?; + Ok(Value::Object(c)) + })(); + i.temp_roots.truncate(mark); + r +} + +/// Adds an item with `text` to the list `o`, which the dialog holds. +fn add_item(i: &mut Interp, o: ObjId, text: &Value) -> JsResult { + // The conversion runs first: it may add or remove items itself. + let text = text_arg(i, text)?; + i.rooted(std::slice::from_ref(&text), |i| { + let win = window_in(i, o, "add")?; + let count = number_slot(i, win, ITEM_COUNT)?; + if count as usize >= MAX_ITEMS { + return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + new_item(i, o, text.clone(), vec![(win, ITEM_COUNT, Value::Number(count + 1.0), 0)]) + }) +} + +/// Adds an item with `text` to the end of the list `o`, making the writes in `more` with it. +fn new_item(i: &mut Interp, o: ObjId, text: Value, more: Vec>) -> JsResult { + let proto = classes(i)?.item_proto; + i.rooted(std::slice::from_ref(&text), |i| { + i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(4)))?; + let item = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + i.rooted(&[Value::Object(item)], |i| { + set_slot(i, item, LIST, Value::Object(o))?; + set_open(i, item, "text", text.clone())?; + append(i, o, ITEMS, "items", Value::Object(item), more)?; + Ok(Value::Object(item)) + }) + }) +} + +/// Gives the new list `o`, which has no items yet, an item for each of `texts`, building its +/// arrays of items once, without counting them in the dialog's items. → how many were added. +fn new_items(i: &mut Interp, o: ObjId, texts: &[Value]) -> JsResult { + let proto = classes(i)?.item_proto; + let mark = i.temp_roots.len(); + let r = (|| { + let mut items = Vec::with_capacity(texts.len()); + for text in texts { + i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(4)))?; + let item = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + i.temp_roots.push(Value::Object(item)); + set_slot(i, item, LIST, Value::Object(o))?; + set_open(i, item, "text", text.clone())?; + items.push(Value::Object(item)); + } + let kept = list(i, &items, false)?; + i.temp_roots.push(Value::Object(kept)); + set_items(i, o, kept)?; + let copy = list(i, &items, true)?; + set_open(i, o, "items", Value::Object(copy))?; + Ok(items.len()) + })(); + i.temp_roots.truncate(mark); + r +} + +fn list_of(i: &mut Interp, this: &Value, what: &str) -> JsResult { + match kind_of(i, this)? { + Some((o, kind)) if kind == "dropdownlist" || kind == "listbox" => Ok(o), + _ => Err(i.type_error(&format!("{what}: this is not a list"))), + } +} + +fn items_of(i: &Interp, o: ObjId) -> JsResult> { + match object_slot(i, o, ITEMS)? { + Some(a) => list_values(i, a), + None => Ok(Vec::new()), + } +} + +fn selection_index(i: &Interp, o: ObjId) -> JsResult> { + let n = number_slot(i, o, SELECTION)?; + Ok((n >= 0.0).then_some(n as usize)) +} + +fn selection_get(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let o = list_of(i, &this, "selection")?; + let items = items_of(i, o)?; + Ok(selection_index(i, o)?.and_then(|n| items.get(n).cloned()).unwrap_or(Value::Null)) +} + +fn selection_set(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = list_of(i, &this, "selection")?; + let items = items_of(i, o)?; + let v = arg(args, 0); + let n = match &v { + Value::Undefined | Value::Null => -1.0, + Value::Number(n) if n.fract() == 0.0 && *n >= 0.0 && (*n as usize) < items.len() => *n, + Value::Number(n) => return Err(range(i, &format!("selection: the list has no item {n}"))), + v => match items.iter().position(|item| same(item, v)) { + Some(n) => n as f64, + None => return Err(i.type_error("selection: give an item of this list, its index or null")), + }, + }; + set_slot(i, o, SELECTION, Value::Number(n))?; + Ok(Value::Undefined) +} + +/// The list an item belongs to and its index there. +fn item_place(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, Option)> { + let list = match this.as_object() { + Some(o) => object_slot(i, o, LIST)?, + None => None, + }; + let Some(list) = list else { return Err(i.type_error(&format!("{what}: this is not a list item"))) }; + let index = items_of(i, list)?.iter().position(|item| same(item, this)); + Ok((list, index)) +} + +fn item_index(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (_, index) = item_place(i, &this, "index")?; + Ok(Value::Number(index.map_or(-1.0, |n| n as f64))) +} + +fn item_selected_get(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (list, index) = item_place(i, &this, "selected")?; + Ok(Value::Bool(index.is_some() && selection_index(i, list)? == index)) +} + +fn item_selected_set(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (list, index) = item_place(i, &this, "selected")?; + let Some(index) = index else { return Ok(Value::Undefined) }; + if arg(args, 0).truthy() { + set_slot(i, list, SELECTION, Value::Number(index as f64))?; + } else if selection_index(i, list)? == Some(index) { + set_slot(i, list, SELECTION, Value::Number(-1.0))?; + } + Ok(Value::Undefined) +} + +fn item_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + item_place(i, &this, "toString")?; + let text = i.get_value(&this, &key("text"))?; + Ok(Value::String(i.to_str(&text)?)) +} + +/// `list.removeAll()`. +fn remove_all(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let o = list_of(i, &this, "removeAll")?; + let win = window_in(i, o, "removeAll")?; + let n = items_of(i, o)?.len() as f64; + let count = number_slot(i, win, ITEM_COUNT)?; + // Both empty arrays are made before the first write, so a run that ends here leaves the list + // and the dialog's count of items as they were. + let kept = Value::Object(list(i, &[], false)?); + i.rooted(std::slice::from_ref(&kept), |i| { + let items = Value::Object(list(i, &[], true)?); + let mut writes = vec![(win, ITEM_COUNT, Value::Number((count - n).max(0.0)), 0)]; + writes.extend(item_writes(i, o, kept.clone(), items)?); + writes.push((o, SELECTION, Value::Number(-1.0), 0)); + write_all(i, writes) + })?; + Ok(Value::Undefined) +} + +fn kids_of(i: &Interp, o: ObjId) -> JsResult> { + match object_slot(i, o, KIDS)? { + Some(a) => list_values(i, a), + None => Ok(Vec::new()), + } +} + +/// `findElement(name)`: the first control in the element, in order, whose `name` is `name`. +fn find_element(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "findElement")?; + let want = i.to_str(&arg(args, 0))?; + let mark = i.temp_roots.len(); + let r = (|| { + // The controls still to look at stay rooted while a `name` getter runs, and each one is + // looked at only while the element still holds it. + let mut stack: Vec = kids_of(i, o)?.into_iter().rev().collect(); + i.temp_roots.extend(stack.iter().cloned()); + while let Some(v) = stack.pop() { + i.use_fuel()?; + let Some(c) = v.as_object() else { continue }; + if !holds(i, o, c)? { + continue; + } + let name = i.get_value(&v, &key("name"))?; + if !holds(i, o, c)? { + continue; + } + if matches!(&name, Value::String(s) if *s == want) { + return Ok(v); + } + let kids = kids_of(i, c)?; + i.temp_roots.extend(kids.iter().cloned()); + stack.extend(kids.into_iter().rev()); + } + Ok(Value::Null) + })(); + i.temp_roots.truncate(mark); + r +} + +/// Does the element `top` hold the control `c`: does each container from `c`'s up to `top` hold +/// the one below? +fn holds(i: &Interp, top: ObjId, c: ObjId) -> JsResult { + let mut at = c; + for _ in 0..=MAX_DEPTH { + let Some(p) = object_slot(i, at, PARENT)? else { return Ok(false) }; + if !kids_of(i, p)?.iter().any(|k| same(k, &Value::Object(at))) { + return Ok(false); + } + if p == top { + return Ok(true); + } + at = p; + } + Ok(false) +} + +/// Calls the element's handler `name` when it has one. → its result, or `None` without one. +fn handler(i: &mut Interp, o: ObjId, name: &str) -> JsResult> { + let f = i.get_value(&Value::Object(o), &key(name))?; + if !i.is_callable(&f) { + return Ok(None); + } + i.call(&f, &Value::Object(o), &[]).map(Some) +} + +/// The radio buttons that form a set with `c`: it and the radio buttons next to it in its +/// container, up to the first control of another kind on each side. +fn radio_set_of(i: &Interp, c: ObjId) -> JsResult> { + let Some(parent) = object_slot(i, c, PARENT)? else { return Ok(vec![c]) }; + let kids = kids_of(i, parent)?; + let Some(at) = kids.iter().position(|k| same(k, &Value::Object(c))) else { return Ok(vec![c]) }; + let radio = |v: &Value| -> JsResult> { + Ok(match kind_of(i, v)? { + Some((o, k)) if k == "radiobutton" => Some(o), + _ => None, + }) + }; + let mut set = vec![c]; + for k in kids[..at].iter().rev() { + let Some(o) = radio(k)? else { break }; + set.push(o); + } + for k in &kids[at + 1..] { + let Some(o) = radio(k)? else { break }; + set.push(o); + } + Ok(set) +} + +fn radio_get(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "value")?; + Ok(Value::Bool(slot(i, o, VALUE)?.truthy())) +} + +/// A radio button's `value`: true turns the other radio buttons of its set off. +fn radio_set(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "value")?; + let on = arg(args, 0).truthy(); + if on { + for other in radio_set_of(i, o)? { + if other != o { + set_slot(i, other, VALUE, Value::Bool(false))?; + } + } + } + set_slot(i, o, VALUE, Value::Bool(on))?; + Ok(Value::Undefined) +} + +/// A listener registered on an element: its event type, handler, capture flag and registration +/// number. +type Listener = (Value, Value, bool, f64); + +/// The listeners registered on `o`, in the order they were added. +fn listeners_of(i: &Interp, o: ObjId) -> JsResult> { + let flat = match object_slot(i, o, LISTENERS)? { + Some(a) => list_values(i, a)?, + None => Vec::new(), + }; + Ok(flat + .as_chunks::<4>() + .0 + .iter() + .map(|[t, f, c, n]| (t.clone(), f.clone(), c.truthy(), if let Value::Number(n) = n { *n } else { 0.0 })) + .collect()) +} + +fn set_listeners(i: &mut Interp, o: ObjId, all: &[Listener]) -> JsResult<()> { + let flat: Vec = all.iter().flat_map(|(t, f, c, n)| [t.clone(), f.clone(), Value::Bool(*c), Value::Number(*n)]).collect(); + i.rooted(&flat.clone(), |i| { + let kept = list(i, &flat, false)?; + set_slot(i, o, LISTENERS, Value::Object(kept)) + }) +} + +/// Is the stored event type `t` the type `ty`? +fn is_type(t: &Value, ty: &str) -> bool { + matches!(t, Value::String(s) if s.to_rust_string() == ty) +} + +/// The event type `addEventListener` and `removeEventListener` were given, checked. +fn event_type(i: &mut Interp, v: &Value, what: &str) -> JsResult<&'static str> { + let text = i.to_str(v)?.to_rust_string(); + if let Some(name) = EVENTS.iter().find(|e| **e == text) { + return Ok(name); + } + if EVENTS_LATER.contains(&text.as_str()) { + return Err(error(i, &format!("{what}: the event {text} is not available yet"))); + } + Err(error(i, &format!("{what}: there is no event {}", text.chars().take(64).collect::()))) +} + +/// `addEventListener(type, handler[, capture])`. +fn add_event_listener(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, 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")); + } + 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"))); + } + // A listener removed and added again is a new registration, which an event already + // running does not reach. + let n = number_slot(i, o, REGISTERED)? + 1.0; + set_slot(i, o, REGISTERED, Value::Number(n))?; + all.push((Value::str(ty), f, capture, n)); + set_listeners(i, o, &all)?; + } + Ok(Value::Undefined) +} + +/// `removeEventListener(type, handler[, capture])`. +fn remove_event_listener(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "removeEventListener")?; + let ty = event_type(i, &arg(args, 0), "removeEventListener")?; + let f = arg(args, 1); + let capture = arg(args, 2).truthy(); + let mut all = listeners_of(i, o)?; + let before = all.len(); + all.retain(|(t, g, c, _)| !(is_type(t, ty) && same(g, &f) && *c == capture)); + if all.len() != before { + set_listeners(i, o, &all)?; + } + Ok(Value::Undefined) +} + +/// `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() + && classes(i)?.dispatching.contains(&o) + { + set_slot(i, o, STOPPED, Value::Bool(true))?; + } + Ok(Value::Undefined) +} + +/// Runs the listeners for `ty` on `at` (only those for `capture` unless it is `None`), with `event`, +/// in the order they were added. A listener that an earlier one removed does not run, even when +/// it was added again, and neither does one registered after `cutoff`, the last registration on +/// `at` when the event started. +fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, event: ObjId, phase: f64, cutoff: f64) -> JsResult { + let wanted = |i: &Interp| -> JsResult> { + Ok(listeners_of(i, at)? + .into_iter() + .filter(|(t, _, c, n)| is_type(t, ty) && capture.is_none_or(|want| *c == want) && *n <= cutoff) + .map(|(_, f, _, n)| (f, n)) + .collect()) + }; + let first = wanted(i)?; + if first.is_empty() { + return Ok(false); + } + 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, n) in &first { + if !wanted(i)?.iter().any(|(_, m)| m == n) { + continue; + } + i.call(f, &Value::Object(at), &[Value::Object(event)])?; + } + Ok(true) + }) +} + +/// Runs the event `ty` on the element `target`: the listeners of the containers above it that +/// capture, its `callback`, its own listeners, then the listeners of the containers that do not +/// capture, until one stops it. → whether the 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. 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. A chain longer than a dialog's nesting +/// allows comes from objects a script made to look like elements, and is a `TypeError`. +fn containers_above(i: &mut Interp, target: ObjId) -> JsResult> { + let mut above = Vec::new(); + let mut at = object_slot(i, target, PARENT)?; + while let Some(p) = at { + i.use_fuel()?; + if above.len() > MAX_DEPTH { + return Err(i.type_error("the event's target is not a ScriptUI window or control")); + } + above.push(p); + at = object_slot(i, p, PARENT)?; + } + Ok(above) +} + +/// 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))?; + set_open(i, event, "target", Value::Object(target))?; + set_open(i, event, "bubbles", Value::Bool(bubbles))?; + set_open(i, event, "cancelable", Value::Bool(false))?; + set_open(i, event, "detail", Value::Number(if ty == "click" { 1.0 } else { 0.0 }))?; + let stopped = |i: &Interp| -> JsResult { Ok(slot(i, event, STOPPED)?.truthy()) }; + // A listener registered once the event started does not hear it, in any phase. + let cutoff = |i: &Interp, o: ObjId| number_slot(i, o, REGISTERED); + let target_cutoff = cutoff(i, target)?; + let cutoffs = above.iter().map(|p| cutoff(i, *p)).collect::>>()?; + for (p, n) in above.iter().zip(&cutoffs).rev() { + if !containers_above(i, target)?.contains(p) { + continue; + } + run_listeners(i, *p, ty, Some(true), event, 1.0, *n)?; + if stopped(i)? { + return Ok(true); + } + } + let had = handler(i, target, callback)?.is_some(); + let heard = run_listeners(i, target, ty, None, event, 2.0, target_cutoff)?; + if bubbles && !stopped(i)? { + for (p, n) in above.iter().zip(&cutoffs) { + if !containers_above(i, target)?.contains(p) { + continue; + } + run_listeners(i, *p, ty, Some(false), event, 3.0, *n)?; + if stopped(i)? { + break; + } + } + } + Ok(had || heard) + }) +} + +/// A click on the control `c` of `kind`: a check box turns over and a radio button turns on, then +/// the click runs. → whether the 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(); + i.put(c, key("value"), Value::Bool(!on), true)?; + } else if kind == "radiobutton" { + i.put(c, key("value"), Value::Bool(true), true)?; + } + dispatch(i, c, "click", "onClick") +} + +/// `notify([event])`: simulates the control's `onClick`, `onChange` or `onChanging`. +fn notify(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, kind) = element(i, &this, "notify")?; + let event = match arg(args, 0) { + Value::Undefined if matches!(kind.as_str(), "button" | "checkbox" | "radiobutton") => "onClick".to_string(), + Value::Undefined => "onChange".to_string(), + v => i.to_str(&v)?.to_rust_string(), + }; + match event.as_str() { + "onClick" => click_control(i, o, &kind)?, + "onChange" => dispatch(i, o, "change", "onChange")?, + "onChanging" => dispatch(i, o, "changing", "onChanging")?, + _ => return Err(error(i, "notify: give onClick, onChange or onChanging")), + }; + Ok(Value::Undefined) +} + +/// The index in `values` that `what` names: an index, one of the values, or a text that an +/// element's `text` equals. A text is converted before the values are read. +fn index_named(i: &mut Interp, what: &Value, values: impl Fn(&Interp) -> JsResult>) -> JsResult<(Vec, Option)> { + match what { + Value::Number(n) => { + let all = values(i)?; + let at = (*n >= 0.0 && n.fract() == 0.0 && (*n as usize) < all.len()).then_some(*n as usize); + Ok((all, at)) + } + Value::Object(_) => { + let all = values(i)?; + let at = all.iter().position(|v| same(v, what)); + Ok((all, at)) + } + v => { + let want = i.to_str(v)?; + let all = values(i)?; + i.rooted(&all.clone(), |i| { + for (n, item) in all.iter().enumerate() { + i.use_fuel()?; + let t = i.get_value(item, &key("text"))?; + if matches!(&t, Value::String(s) if *s == want) { + return Ok((all.clone(), Some(n))); + } + } + Ok((all.clone(), None)) + }) + } + } +} + +/// `list.find(text)`: the first item whose text is `text`, or `null`. +fn find(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = list_of(i, &this, "find")?; + let text = Value::String(i.to_str(&arg(args, 0))?); + let (items, at) = index_named(i, &text, |i| items_of(i, o))?; + Ok(at.and_then(|n| items.get(n).cloned()).unwrap_or(Value::Null)) +} + +/// The controls `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 the number of their list +/// items. +fn subtree(i: &mut Interp, c: &Value) -> JsResult<(Vec, f64)> { + let (mut controls, mut items) = (Vec::new(), 0.0); + let mut stack = vec![c.clone()]; + while let Some(v) = stack.pop() { + i.use_fuel()?; + let Some(o) = v.as_object() else { continue }; + controls.push(o); + items += items_of(i, o)?.len() as f64; + stack.extend(own_kids(i, o)?); + } + Ok((controls, items)) +} + +/// `remove(what)`: removes a list's item, or a container's control, given by its index, the +/// object itself or its text. Nothing happens when there is no such item or control. +fn remove(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, kind) = element(i, &this, "remove")?; + let what = arg(args, 0); + 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)))?; + // 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_in(i, o, "remove")?; + let Some(at) = at else { return Ok(Value::Undefined) }; + items.remove(at); + let count = number_slot(i, win, ITEM_COUNT)?; + let selection = match selection_index(i, o)? { + Some(n) if n == at => Some(-1.0), + Some(n) if n > at => Some((n - 1) as f64), + _ => None, + }; + // Both arrays are made before the first write, so a run that ends here leaves the list, + // its selection and the dialog's count of items as they were. + i.rooted(&items.clone(), |i| { + let kept = Value::Object(list(i, &items, false)?); + i.rooted(std::slice::from_ref(&kept), |i| { + let copy = Value::Object(list(i, &items, true)?); + let mut writes = item_writes(i, o, kept.clone(), copy)?.to_vec(); + writes.push((win, ITEM_COUNT, Value::Number((count - 1.0).max(0.0)), 0)); + writes.extend(selection.map(|n| (o, SELECTION, Value::Number(n), 0))); + write_all(i, writes) + }) + })?; + return Ok(Value::Undefined); + } + if !matches!(kind.as_str(), "dialog" | "group" | "panel") { + return Err(error(i, &format!("remove: a {kind} holds no controls or items"))); + } + let before = slot(i, o, KIDS)?; + let (mut kids, at) = i.rooted(std::slice::from_ref(&before), |i| index_named(i, &what, |i| kids_of(i, o)))?; + // A `text` getter read during the lookup may have changed the container or removed it. + if !same(&slot(i, o, KIDS)?, &before) { + return Err(error(i, "remove: the container's controls changed while the control was looked up")); + } + let win = window_in(i, o, "remove")?; + let Some(at) = at else { return Ok(Value::Undefined) }; + if !matches!(kids.get(at).and_then(Value::as_object), Some(c) if object_slot(i, c, PARENT)? == Some(o)) { + return Err(i.type_error("remove: this is not a ScriptUI window or control")); + } + let gone = kids.remove(at); + let Some(root) = gone.as_object() else { return Ok(Value::Undefined) }; + let mut keep = kids.clone(); + keep.push(gone); + i.rooted(&keep, |i| { + // Everything that can fail runs before the first change, so a run that ends here (out of + // fuel or memory) leaves the container, the dialog's counts and the control as they were. + let (controls, items) = subtree(i, &keep[keep.len() - 1])?; + let kept = Value::Object(list(i, &kids, false)?); + i.rooted(std::slice::from_ref(&kept), |i| { + let copy = Value::Object(list(i, &kids, true)?); + i.rooted(std::slice::from_ref(©), |i| { + let count = number_slot(i, win, COUNT)?; + let total = number_slot(i, win, ITEM_COUNT)?; + let mut writes = vec![ + (o, KIDS, kept.clone(), 0), + (o, "children", copy.clone(), OPEN), + (win, COUNT, Value::Number((count - controls.len() as f64).max(0.0)), 0), + (win, ITEM_COUNT, Value::Number((total - items).max(0.0)), 0), + ]; + writes.extend(detached(root, &controls)); + // The heap grows only by the properties a write adds, so the room for them is + // checked once, before the first write. + let mut growth = 0; + for (at, name, _, _) in &writes { + if !i.object(*at)?.props.contains(&key(name)) { + growth += PROP_BYTES + string_bytes(name.len()); + } + } + i.reserve_heap(growth)?; + for (at, name, value, flags) in writes { + i.define(at, key(name), Prop::Data { value, flags })?; + } + Ok(()) + }) + }) + })?; + Ok(Value::Undefined) +} + +/// The writes that take the control `root`, removed from its container, out of the dialog: it has +/// no container, and neither it nor `controls`, the controls it holds, belong to the dialog any +/// longer, so their `window` is `null`. +fn detached(root: ObjId, controls: &[ObjId]) -> Vec<(ObjId, &'static str, Value, u8)> { + let mut writes = Vec::with_capacity(2 * controls.len() + 2); + for &o in controls { + writes.push((o, WINDOW, Value::Null, 0)); + writes.push((o, "window", Value::Null, OPEN)); + } + writes.push((root, PARENT, Value::Null, 0)); + writes.push((root, "parent", Value::Null, OPEN)); + writes +} + +fn control_show(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "show")?; + i.put(o, key("visible"), Value::Bool(true), true)?; + Ok(Value::Undefined) +} + +fn control_hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "hide")?; + i.put(o, key("visible"), Value::Bool(false), true)?; + Ok(Value::Undefined) +} + +fn nothing(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Undefined) +} + +fn dialog_of(i: &mut Interp, this: &Value, what: &str) -> JsResult { + match kind_of(i, this)? { + Some((o, kind)) if kind == "dialog" => Ok(o), + _ => Err(i.type_error(&format!("{what}: this is not a ScriptUI window"))), + } +} + +/// `close([result])`: closes the dialog that is showing once the running handler returns. +fn close(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = dialog_of(i, &this, "close")?; + let result = match arg(args, 0) { + Value::Undefined => 0.0, + v => number_arg(i, &v, "close: the result")?, + }; + if classes(i)?.showing == Some(o) { + set_slot(i, o, CLOSING, Value::Number(result))?; + } + Ok(Value::Undefined) +} + +/// `hide()`: closes the dialog that is showing with the result 0. +fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + close(i, this, &[], false) +} + +fn host_fn(i: &mut Interp, name: &str) -> JsResult { + let host = classes(i)?.host; + i.get_value(&Value::Object(host), &key(name)) +} + +fn set_showing(i: &mut Interp, showing: Option) { + if let Some(c) = i.script_ui.as_mut() { + c.showing = showing; + } +} + +/// `show()` on a dialog: gives its description to the host's `open`, then runs it ([`opened`]). +fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult { + let win = dialog_of(i, &this, "show")?; + match classes(i)?.showing { + Some(o) if o == win => return Err(error(i, "show: this dialog is already showing")), + Some(_) => return Err(error(i, "show: a dialog cannot open while another dialog is showing")), + None => {} + } + set_showing(i, Some(win)); + set_slot(i, win, CLOSING, Value::Undefined)?; + let described = describe(i, win); + let (desc, nodes, def, cancel, lists) = match described { + Ok(d) => d, + Err(e) => { + set_showing(i, None); + return Err(e); + } + }; + let open = match host_fn(i, "open") { + Ok(open) => open, + Err(e) => { + set_showing(i, None); + return Err(e); + } + }; + Ok(Pause { + host: open, + args: vec![desc], + keep: vec![Value::Object(win), Value::Object(nodes), Value::Number(def), Value::Number(cancel), Value::Object(lists)], + resume: opened, + failed: Some(failed), + }) +} + +/// A host call of `show()` failed, or a handler threw: the dialog is no longer showing. +fn failed(i: &mut Interp, keep: &[Value]) { + let Some(win) = arg(keep, 0).as_object() else { return }; + if classes(i).ok().and_then(|c| c.showing) != Some(win) { + return; + } + set_showing(i, None); + if let Ok(end) = host_fn(i, "end") { + let _ = i.call(&end, &Value::Undefined, &[Value::Number(0.0), Value::Bool(false)]); + } +} + +/// `show()` ends with `result`. +fn finish(i: &mut Interp, win: ObjId, result: f64) -> JsResult { + set_showing(i, None); + set_slot(i, win, CLOSING, Value::Undefined)?; + let end = host_fn(i, "end")?; + i.call(&end, &Value::Undefined, &[Value::Number(result), Value::Bool(true)])?; + Ok(Value::Number(result)) +} + +/// Runs `onClose`. → false when it returned `false`. A `close()` that `onClose` calls belongs to +/// the close it decides on, so after `false` the dialog waits for the next event. +fn may_close(i: &mut Interp, win: ObjId) -> JsResult { + let closes = !matches!(handler(i, win, "onClose")?, Some(Value::Bool(false))); + if !closes { + set_slot(i, win, CLOSING, Value::Undefined)?; + } + Ok(closes) +} + +/// Closes the dialog when a handler asked to, or asks the host's `wait` what happens next. +fn next(i: &mut Interp, win: ObjId) -> JsResult { + loop { + i.use_fuel()?; + if let Value::Number(result) = slot(i, win, CLOSING)? { + set_slot(i, win, CLOSING, Value::Undefined)?; + if may_close(i, win)? { + return finish(i, win, result); + } + continue; + } + let (desc, nodes, def, cancel, lists) = describe(i, win)?; + // A getter that `describe` ran may have closed the dialog. + if matches!(slot(i, win, CLOSING)?, Value::Number(_)) { + continue; + } + let wait = host_fn(i, "wait")?; + i.again = Some(Pause { + host: wait, + args: vec![desc], + keep: vec![Value::Object(win), Value::Object(nodes), Value::Number(def), Value::Number(cancel), Value::Object(lists)], + resume: answered, + failed: Some(failed), + }); + return Ok(Value::Undefined); + } +} + +/// Runs `r`; when it fails, the dialog is no longer showing. +fn guarded(i: &mut Interp, keep: &[Value], r: impl FnOnce(&mut Interp) -> JsResult) -> JsResult { + let v = r(i); + if let Err(e) = &v { + // The thrown value stays kept from collection while `failed` runs. + let thrown = match e { + Abrupt::Throw(t) => vec![t.clone()], + _ => Vec::new(), + }; + let mark = i.temp_roots.len(); + i.temp_roots.extend(thrown); + failed(i, keep); + i.temp_roots.truncate(mark); + } + v +} + +fn opened(i: &mut Interp, keep: &[Value], _: Value) -> JsResult { + guarded(i, keep, |i| { + let Some(win) = arg(keep, 0).as_object() else { return Err(Abrupt::Internal("show lost its dialog".into())) }; + dispatch(i, win, "show", "onShow")?; + next(i, win) + }) +} + +/// What the host's `wait` gave: the event, which the dialog takes, and what happens next. +fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { + guarded(i, keep, |i| { + let (Some(win), Some(nodes)) = (arg(keep, 0).as_object(), arg(keep, 1).as_object()) else { + return Err(Abrupt::Internal("show lost its dialog".into())); + }; + let Some(ev) = answer.as_object() else { return Err(Abrupt::Internal("the host gave show no event".into())) }; + let event = match slot(i, ev, "event")? { + Value::String(s) => s.to_rust_string(), + _ => String::new(), + }; + if event == "close" { + if may_close(i, win)? { + return finish(i, win, 0.0); + } + return next(i, win); + } + let id = match slot(i, ev, "id")? { + Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => n as usize, + _ => return Err(Abrupt::Internal("the host gave show an event without a control".into())), + }; + let nodes = list_values(i, nodes)?; + let Some((c, kind)) = nodes.get(id).map(|v| kind_of(i, v)).transpose()?.flatten() else { + return Err(Abrupt::Internal("the host gave show an event for a control the dialog does not hold".into())); + }; + let value = slot(i, ev, "value")?; + match event.as_str() { + "click" => { + // A listener above the button that closed the dialog gives the result. + if !click_control(i, c, &kind)? && kind == "button" && matches!(slot(i, win, CLOSING)?, Value::Undefined) { + let is = |k: usize| matches!(arg(keep, k), Value::Number(n) if n == id as f64); + if is(2) { + set_slot(i, win, CLOSING, Value::Number(1.0))?; + } else if is(3) { + set_slot(i, win, CLOSING, Value::Number(2.0))?; + } + } + } + "change" => { + match kind.as_str() { + "edittext" => { + i.put(c, key("text"), value, true)?; + dispatch(i, c, "changing", "onChanging")?; + } + "slider" => { + i.put(c, key("value"), value, true)?; + dispatch(i, c, "changing", "onChanging")?; + } + _ => { + let n = match value { + Value::Number(n) => n, + _ => -1.0, + }; + // The index is into the items the person saw. + let shown = match arg(keep, 4).as_object() { + Some(lists) => list_values(i, lists)?.get(id).cloned().unwrap_or(Value::Undefined), + None => Value::Undefined, + }; + if !same(&slot(i, c, ITEMS)?, &shown) { + return Err(error(i, "show: a list's items changed before the person's choice was taken")); + } + set_slot(i, c, SELECTION, Value::Number(n))?; + } + } + dispatch(i, c, "change", "onChange")?; + } + _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), + } + next(i, win) + }) +} + +fn text_of(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let s = i.to_str(v)?; + let text = if s.len() > MAX_TEXT_BYTES { None } else { Some(s.to_rust_string()) }; + match text { + Some(t) if t.len() <= MAX_TEXT_BYTES => Ok(t), + _ => Err(range(i, &format!("show: {what} is longer than 16 KiB"))), + } +} + +fn get(i: &mut Interp, o: ObjId, name: &str) -> JsResult { + i.get_value(&Value::Object(o), &key(name)) +} + +/// [`get`], keeping the value in the roots [`describe`] lets go of when it returns. +fn get_kept(i: &mut Interp, o: ObjId, name: &str) -> JsResult { + let v = get(i, o, name)?; + i.temp_roots.push(v.clone()); + Ok(v) +} + +fn number_of(i: &mut Interp, o: ObjId, name: &str) -> JsResult { + let v = get(i, o, name)?; + Ok(Data::Number(number_arg(i, &v, &format!("show: a control's {name}"))?)) +} + +/// An alignment: a name, or an array of a horizontal and a vertical name; `null` when not set. +fn alignment(i: &mut Interp, v: &Value) -> JsResult { + match v { + Value::Undefined | Value::Null => Ok(Data::Null), + Value::Object(a) if matches!(i.object(*a)?.class, Class::Array { .. }) => { + let mut out = Vec::new(); + for n in 0..2 { + let part = i.get_value(v, &index_key(n))?; + out.push(Data::String(text_of(i, &part, "an alignment")?.to_lowercase())); + } + Ok(Data::Array(out)) + } + v => Ok(Data::String(text_of(i, v, "an alignment")?.to_lowercase())), + } +} + +/// Numbers read from `v`'s indices, or else from its properties `names`. +fn numbers(i: &mut Interp, v: &Value, names: &[&str], what: &str) -> JsResult { + let Some(o) = v.as_object() else { + if matches!(v, Value::Undefined | Value::Null) { + return Ok(Data::Null); + } + return Err(i.type_error(&format!("show: give {what} as an array or an object"))); + }; + let array = matches!(i.object(o)?.class, Class::Array { .. }); + let mut out = Vec::new(); + for (n, name) in names.iter().enumerate() { + let part = if array { i.get_value(v, &index_key(n as u32))? } else { i.get_value(v, &key(name))? }; + out.push(Data::Number(number_arg(i, &part, &format!("show: {what}"))?)); + } + Ok(Data::Array(out)) +} + +/// Bounds as `[left, top, right, bottom]`: from an array, from `x`, `y`, `width` and `height`, or +/// from `left`, `top`, `right` and `bottom`. +fn bounds(i: &mut Interp, v: &Value) -> JsResult { + if let Some(o) = v.as_object() + && !matches!(i.object(o)?.class, Class::Array { .. }) + && !matches!(i.get_value(v, &key("width"))?, Value::Undefined) + { + let Data::Array(xywh) = numbers(i, v, &["x", "y", "width", "height"], "bounds")? else { return Ok(Data::Null) }; + let n = |k: usize| match xywh.get(k) { + Some(Data::Number(n)) => *n, + _ => 0.0, + }; + return Ok(Data::Array(vec![Data::Number(n(0)), Data::Number(n(1)), Data::Number(n(0) + n(2)), Data::Number(n(1) + n(3))])); + } + numbers(i, v, &["left", "top", "right", "bottom"], "bounds") +} + +/// `base`'s width and height, each replaced by `over`'s when that is above 0. +fn overridden(base: Data, over: Data) -> Data { + let Data::Array(over) = over else { return base }; + let mut out = match base { + Data::Array(b) => b, + _ => vec![Data::Number(-1.0), Data::Number(-1.0)], + }; + for (o, v) in out.iter_mut().zip(over) { + if matches!(v, Data::Number(n) if n > 0.0) { + *o = v; + } + } + Data::Array(out) +} + +fn margins(i: &mut Interp, v: &Value) -> JsResult { + if v.as_object().is_some() { + return numbers(i, v, &["left", "top", "right", "bottom"], "margins"); + } + let m = number_arg(i, v, "show: margins")?; + Ok(Data::Array(vec![Data::Number(m); 4])) +} + +/// The dialog's description: its elements in order, each after the container that holds it, as +/// [`Data`] for the host's `open` and `wait`, with the elements in that order, and the indices of +/// its default and cancel elements (-1 for none), and each element's array of list items as it +/// was described (`undefined` for an element that is not a list). When a getter changes a list or +/// a list item's text, or adds or removes a control, after it was read, the dialog is read again +/// once; a dialog that changes again throws an `Error`. +fn describe(i: &mut Interp, win: ObjId) -> JsResult { + for _ in 0..2 { + let mark = i.temp_roots.len(); + let r = describe_rooted(i, win); + i.temp_roots.truncate(mark); + if let Some(d) = r? { + return Ok(d); + } + } + Err(error(i, "show: a list's items or a container's controls changed while the dialog was read")) +} + +/// A description, the elements in its order, the default and cancel elements, and the lists' items. +type Described = (Value, ObjId, f64, f64, ObjId); + +/// Has each list in `order` the array of items and the selection it had when it was described? +fn lists_unchanged(i: &Interp, order: &[(ObjId, String, f64)], snapshot: &[Value], selections: &[f64]) -> JsResult { + for (((o, ..), kept), sel) in order.iter().zip(snapshot).zip(selections) { + if !matches!(kept, Value::Undefined) && (!same(&slot(i, *o, ITEMS)?, kept) || number_slot(i, *o, SELECTION)? != *sel) { + return Ok(false); + } + } + Ok(true) +} + +/// Has each list item in `texts` the text it had when it was read? +fn texts_unchanged(i: &Interp, texts: &[(ObjId, Value)]) -> JsResult { + for (item, read) in texts { + match i.get_own_property(*item, &key("text"))? { + Some(Prop::Data { value, .. }) if crate::interp::same_value(&value, read) => {} + _ => return Ok(false), + } + } + Ok(true) +} + +/// Has each element in `order` the array of controls it had when the dialog was read? +fn tree_unchanged(i: &Interp, order: &[(ObjId, String, f64)], tree: &[Value]) -> JsResult { + for ((o, ..), kept) in order.iter().zip(tree) { + let now = slot(i, *o, KIDS)?; + if !(same(&now, kept) || matches!((&now, kept), (Value::Undefined, Value::Undefined))) { + return Ok(false); + } + } + Ok(true) +} + +fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { + let mut order: Vec<(ObjId, String, f64)> = Vec::new(); + let mut tree = Vec::new(); + let mut seen = std::collections::HashSet::new(); + let mut stack: Vec<(Value, f64, usize)> = vec![(Value::Object(win), -1.0, 0)]; + while let Some((v, parent, depth)) = stack.pop() { + i.use_fuel()?; + let Some((o, kind)) = kind_of(i, &v)? else { return Err(i.type_error("show: the dialog holds something that is not a control")) }; + if !seen.insert(o) { + return Err(i.type_error("show: a control appears twice in the dialog")); + } + if order.len() > MAX_CONTROLS { + return Err(range(i, &format!("show: a dialog can hold at most {MAX_CONTROLS} controls"))); + } + if depth > MAX_DEPTH { + return Err(range(i, &format!("show: controls can be nested at most {MAX_DEPTH} deep"))); + } + let index = order.len() as f64; + order.push((o, kind, parent)); + // Each container's array of controls as it is read; a change to it means a later getter + // added or removed a control. + let held = slot(i, o, KIDS)?; + i.temp_roots.push(held.clone()); + tree.push(held); + for kid in kids_of(i, o)?.into_iter().rev() { + stack.push((kid, index, depth + 1)); + } + } + let objects: Vec = order.iter().map(|(o, ..)| Value::Object(*o)).collect(); + i.temp_roots.extend(objects.iter().cloned()); + let mut nodes = Vec::with_capacity(order.len()); + let mut names = Vec::with_capacity(order.len()); + let mut items_total = 0usize; + // Each list's array of items as it is read; a change to it means a later getter changed the list. + let mut snapshot = Vec::with_capacity(order.len()); + // Each list's selection as it is read; a later getter may change it. + let mut selections = Vec::with_capacity(order.len()); + // Whether each element, in `order`, is enabled and visible with the containers above it. + let mut live: Vec<(bool, bool)> = Vec::with_capacity(order.len()); + // Each list item's own text as it was read. + let mut item_texts: Vec<(ObjId, Value)> = Vec::new(); + for (o, kind, parent) in &order { + let o = *o; + let mut listed = Value::Undefined; + let mut selected = -1.0; + let name_v = get(i, o, "name")?; + let name = text_of(i, &name_v, "a control's name")?; + let text_v = get(i, o, "text")?; + 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())), + ]; + let enabled = get(i, o, "enabled")?.truthy(); + let visible = get(i, o, "visible")?.truthy(); + // A control is enabled and visible only while every container above it is. + let (above_enabled, above_visible) = if *parent >= 0.0 { live.get(*parent as usize).copied().unwrap_or((true, true)) } else { (true, true) }; + live.push((enabled && above_enabled, visible && above_visible)); + // Enter and Escape click a button found by its name or text only when it can be clicked. + let clickable = kind == "button" && enabled && visible && above_enabled && above_visible; + names.push((clickable, name, text)); + d.push(("enabled".into(), Data::Bool(enabled))); + d.push(("visible".into(), Data::Bool(visible))); + // A value a getter gives is kept from collection while its own properties are read. + let b = get_kept(i, o, "bounds")?; + d.push(("bounds".into(), bounds(i, &b)?)); + // `size` set to a positive width or height takes the place of `preferredSize`'s. + let preferred = get_kept(i, o, "preferredSize")?; + let preferred = numbers(i, &preferred, &["width", "height"], "preferredSize")?; + let set = get_kept(i, o, "size")?; + let set = numbers(i, &set, &["width", "height"], "size")?; + d.push(("size".into(), overridden(preferred, set))); + for (name, field) in [("minimumSize", "min"), ("maximumSize", "max")] { + let v = get_kept(i, o, name)?; + d.push((field.into(), numbers(i, &v, &["width", "height"], name)?)); + } + let a = get_kept(i, o, "alignment")?; + d.push(("alignment".into(), alignment(i, &a)?)); + // The characters a text field or static text reserves room for in its width. + if matches!(kind.as_str(), "edittext" | "statictext") { + let n = get(i, o, "characters")?; + if !matches!(n, Value::Undefined | Value::Null) { + d.push(("characters".into(), Data::Number(number_arg(i, &n, "show: a control's characters")?))); + } + } + if matches!(kind.as_str(), "dialog" | "group" | "panel") { + let orientation = get(i, o, "orientation")?; + d.push(("orientation".into(), Data::String(text_of(i, &orientation, "an orientation")?.to_lowercase()))); + let ac = get_kept(i, o, "alignChildren")?; + d.push(("alignChildren".into(), alignment(i, &ac)?)); + d.push(("spacing".into(), number_of(i, o, "spacing")?)); + let m = get_kept(i, o, "margins")?; + d.push(("margins".into(), margins(i, &m)?)); + } + match kind.as_str() { + "checkbox" | "radiobutton" => { + let on = get(i, o, "value")?.truthy(); + d.push(("value".into(), Data::Bool(on))); + } + "slider" | "progressbar" => { + d.push(("value".into(), number_of(i, o, "value")?)); + d.push(("minvalue".into(), number_of(i, o, "minvalue")?)); + d.push(("maxvalue".into(), number_of(i, o, "maxvalue")?)); + } + "edittext" => { + let props = get_kept(i, o, "properties")?; + let (multiline, readonly) = match props { + Value::Object(_) => (i.get_value(&props, &key("multiline"))?.truthy(), i.get_value(&props, &key("readonly"))?.truthy()), + _ => (false, false), + }; + // The dialog cannot hide what is typed, so a field meant to hide it is refused before it shows. + if props.as_object().is_some() && i.get_value(&props, &key("noecho"))?.truthy() { + return Err(error(i, "show: an edit field that hides its text (noecho) is not available yet")); + } + d.push(("multiline".into(), Data::Bool(multiline))); + d.push(("readonly".into(), Data::Bool(readonly))); + } + "dropdownlist" | "listbox" => { + let kept = slot(i, o, ITEMS)?; + i.temp_roots.push(kept.clone()); + listed = kept; + let items = items_of(i, o)?; + items_total = items_total.saturating_add(items.len()); + if items_total > MAX_ITEMS { + return Err(range(i, &format!("show: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + let mut texts = Vec::with_capacity(items.len()); + for item in &items { + let t = i.get_value(item, &key("text"))?; + // The text as the item holds it; a later getter that changes it changes the list. + if let Some(at) = item.as_object() + && let Some(Prop::Data { value, .. }) = i.get_own_property(at, &key("text"))? + { + i.temp_roots.push(value.clone()); + item_texts.push((at, value)); + } + texts.push(Data::String(text_of(i, &t, "a list item's text")?)); + } + d.push(("items".into(), Data::Array(texts))); + d.push(("itemsRevision".into(), Data::Number(number_slot(i, o, ITEMS_REV)?))); + // The item texts' getters ran above, so the selection is read after them. + selected = number_slot(i, o, SELECTION)?; + let sel = selection_index(i, o)?.filter(|n| *n < items.len()); + d.push(("selection".into(), sel.map_or(Data::Null, |n| Data::Number(n as f64)))); + } + _ => {} + } + nodes.push(Data::Object(d)); + snapshot.push(listed); + selections.push(selected); + } + let target = |i: &mut Interp, name: &str, word: &str| -> JsResult { + let given = get(i, win, name)?; + if let Some(n) = objects.iter().position(|o| same(o, &given)) { + return Ok(n as f64); + } + if !matches!(given, Value::Undefined | Value::Null) { + return Ok(-1.0); + } + let button = |by_name: bool| names.iter().position(|(c, n, t)| *c && (if by_name { n } else { t }).to_lowercase() == word); + Ok(button(true).or_else(|| button(false)).map_or(-1.0, |n| n as f64)) + }; + let def = target(i, "defaultElement", "ok")?; + let cancel = target(i, "cancelElement", "cancel")?; + if !lists_unchanged(i, &order, &snapshot, &selections)? || !tree_unchanged(i, &order, &tree)? || !texts_unchanged(i, &item_texts)? { + return Ok(None); + } + let desc = Data::Object(vec![ + ("nodes".into(), Data::Array(nodes)), + ("defaultElement".into(), Data::Number(def)), + ("cancelElement".into(), Data::Number(cancel)), + ]); + let desc = i.write_data(desc, 0, true)?; + i.temp_roots.push(desc.clone()); + let kept = list(i, &objects, false)?; + i.temp_roots.push(Value::Object(kept)); + let lists = list(i, &snapshot, false)?; + Ok(Some((desc, kept, def, cancel, lists))) +} + +/// Adds `Window`, its prototype's methods, and the host functions in `items`. +pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResult<()> { + let host = i.host_object("Window", items)?; + let object_proto = i.intrinsics.object_proto; + i.rooted(&[Value::Object(host)], |i| { + i.reserve_heap(OBJECT_BYTES.saturating_mul(5))?; + let window_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(window_proto)); + let control_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(control_proto)); + let item_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(item_proto)); + let layout = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(layout)); + let selection_get = native(i, "selection", selection_get, 0, NativeKind::Plain, false)?; + i.temp_roots.push(Value::Object(selection_get)); + let selection_set = native(i, "selection", selection_set, 1, NativeKind::Plain, false)?; + i.temp_roots.push(Value::Object(selection_set)); + let event_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(event_proto)); + let radio_get = native(i, "value", radio_get, 0, NativeKind::Plain, false)?; + i.temp_roots.push(Value::Object(radio_get)); + let radio_set = native(i, "value", radio_set, 1, NativeKind::Plain, false)?; + i.temp_roots.push(Value::Object(radio_set)); + i.script_ui = Some(Classes { + window_proto, + control_proto, + item_proto, + event_proto, + layout, + host, + selection_get, + selection_set, + radio_get, + radio_set, + showing: None, + 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)?; + // `Window.alert`, `Window.confirm` and `Window.prompt` are the host's global functions. + let global = i.global; + for name in ["alert", "confirm", "prompt"] { + if let Some(Prop::Data { value, .. }) = i.get_own_property(global, &key(name))? + && i.is_callable(&value) + { + data(i, window, name, value, HIDDEN)?; + } + } + for proto in [window_proto, control_proto] { + method(i, proto, "add", add, 4)?; + method(i, proto, "findElement", find_element, 1)?; + method(i, proto, "remove", remove, 1)?; + method(i, proto, "addEventListener", add_event_listener, 3)?; + method(i, proto, "removeEventListener", remove_event_listener, 3)?; + } + method(i, window_proto, "close", close, 1)?; + method(i, window_proto, "hide", hide, 0)?; + method(i, window_proto, "center", nothing, 1)?; + pausable_method(i, window_proto, "show", show, 0)?; + method(i, control_proto, "removeAll", remove_all, 0)?; + method(i, control_proto, "find", find, 1)?; + method(i, control_proto, "notify", notify, 1)?; + method(i, control_proto, "show", control_show, 0)?; + method(i, control_proto, "hide", control_hide, 0)?; + method(i, event_proto, "stopPropagation", event_stop, 0)?; + method(i, event_proto, "preventDefault", 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 })?; + let get = native(i, "selected", item_selected_get, 0, NativeKind::Plain, false)?; + let set = native(i, "selected", item_selected_set, 1, NativeKind::Plain, false)?; + i.define(item_proto, key("selected"), Prop::Accessor { get: Some(get), set: Some(set), flags: 0 })?; + method(i, layout, "layout", nothing, 1)?; + method(i, layout, "resize", nothing, 0)?; + i.object_mut(layout)?.extensible = false; + Ok(()) + }) +} diff --git a/crates/js/src/scriptui_resource.rs b/crates/js/src/scriptui_resource.rs new file mode 100644 index 0000000000..6d27cce47b --- /dev/null +++ b/crates/js/src/scriptui_resource.rs @@ -0,0 +1,371 @@ +//! The reader of ScriptUI resource specifications, as the help page +//! describes +//! them: a type, then braces holding property definitions, where a property whose value is a +//! control class followed by braces defines a control the container holds. +//! +//! `[name:] Type { name: value, ... }` is read into a [`Spec`]. A value is `null`, `true`, `false`, +//! a string in single or double quotes, a number, an inline array `[value, ...]`, an inline object +//! `{name: value, ...}`, or, directly in a window's or control's braces, a control `Class { ... }`. +//! A name is an identifier or a quoted string. The commas between properties may be left out, and +//! a comma may end a list. A string longer than [`MAX_BYTES`] or values nested more than +//! [`MAX_NESTING`] deep are refused; these are VectorCraft's own limits. + +/// The most bytes (UTF-8) of a resource specification. +pub const MAX_BYTES: usize = 1 << 20; +/// How deeply braces and brackets nest in a resource specification. +pub const MAX_NESTING: usize = 64; + +/// A value in a resource specification. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Res { + Null, + Bool(bool), + Number(f64), + String(String), + Array(Vec), + Object(Vec<(String, Res)>), + Control(Spec), +} + +/// A window or control: its class as written and its properties in order. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Spec { + pub(crate) class: String, + pub(crate) props: Vec<(String, Res)>, +} + +/// Why a resource specification could not be read. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Fault { + /// The text is not a resource specification; the message says where. + Syntax(String), + /// The text passes [`MAX_BYTES`] or [`MAX_NESTING`]. + Limit(String), +} + +/// Reads `text`, which is `[name:] Type { ... }` with nothing after it but white space. +pub(crate) fn parse(text: &str) -> Result { + if text.len() > MAX_BYTES { + return Err(Fault::Limit(format!("a resource specification is longer than {} MiB", MAX_BYTES >> 20))); + } + let mut r = Reader { chars: text.chars().collect(), at: 0 }; + r.space(); + let quoted = matches!(r.peek(), Some('\'' | '"')); + let first = r.name()?; + r.space(); + let class = if r.eat(':') { + r.space(); + r.ident()? + } else if quoted { + return Err(r.expected(": after the name")); + } else { + first + }; + r.space(); + if !r.eat('{') { + return Err(r.expected("{ after the type")); + } + let props = r.props(true, 1)?; + r.space(); + if r.at < r.chars.len() { + return Err(r.expected("the end of the resource specification")); + } + Ok(Spec { class, props }) +} + +struct Reader { + chars: Vec, + at: usize, +} + +impl Reader { + fn peek(&self) -> Option { + self.chars.get(self.at).copied() + } + + fn eat(&mut self, c: char) -> bool { + if self.peek() == Some(c) { + self.at += 1; + true + } else { + false + } + } + + fn space(&mut self) { + while self.peek().is_some_and(char::is_whitespace) { + self.at += 1; + } + } + + fn expected(&self, what: &str) -> Fault { + match self.peek() { + Some(c) => Fault::Syntax(format!("expected {what} at character {}, found {c:?}", self.at + 1)), + None => Fault::Syntax(format!("expected {what} at character {}, the end of the resource specification", self.at + 1)), + } + } + + fn ident(&mut self) -> Result { + let start = self.at; + while self.peek().is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$') { + self.at += 1; + } + if self.at == start || self.chars[start].is_ascii_digit() { + self.at = start; + return Err(self.expected("a name")); + } + Ok(self.chars[start..self.at].iter().collect()) + } + + /// A property name: an identifier or a quoted string. + fn name(&mut self) -> Result { + match self.peek() { + Some('\'' | '"') => self.string(), + _ => self.ident(), + } + } + + /// The properties after an opening brace, up to and including its closing brace. Controls are + /// allowed among them when `controls`. + fn props(&mut self, controls: bool, depth: usize) -> Result, Fault> { + if depth > MAX_NESTING { + return Err(Fault::Limit(format!("a resource specification nests more than {MAX_NESTING} deep"))); + } + let mut props = Vec::new(); + loop { + self.space(); + if self.eat('}') { + return Ok(props); + } + let name = self.name()?; + self.space(); + if !self.eat(':') { + return Err(self.expected(": after a property name")); + } + self.space(); + let value = self.value(controls, depth)?; + props.push((name, value)); + self.space(); + self.eat(','); + } + } + + fn value(&mut self, controls: bool, depth: usize) -> Result { + match self.peek() { + Some('\'' | '"') => Ok(Res::String(self.string()?)), + Some('[') => { + self.at += 1; + if depth + 1 > MAX_NESTING { + return Err(Fault::Limit(format!("a resource specification nests more than {MAX_NESTING} deep"))); + } + let mut items = Vec::new(); + loop { + self.space(); + if self.eat(']') { + return Ok(Res::Array(items)); + } + items.push(self.value(false, depth + 1)?); + self.space(); + if !self.eat(',') && self.peek() != Some(']') { + return Err(self.expected(", or ] in an array")); + } + } + } + Some('{') => { + self.at += 1; + Ok(Res::Object(self.props(false, depth + 1)?)) + } + Some(c) if c.is_ascii_digit() || matches!(c, '-' | '+' | '.') => self.number(), + Some(_) => { + let start = self.at; + let word = self.ident()?; + match word.as_str() { + "null" => return Ok(Res::Null), + "true" => return Ok(Res::Bool(true)), + "false" => return Ok(Res::Bool(false)), + _ => {} + } + self.space(); + if self.peek() != Some('{') { + self.at = start; + return Err(self.expected("a value")); + } + if !controls { + self.at = start; + return Err(self.expected("a value (a control can only be a property of a window or a container)")); + } + self.at += 1; + Ok(Res::Control(Spec { class: word, props: self.props(true, depth + 1)? })) + } + None => Err(self.expected("a value")), + } + } + + fn number(&mut self) -> Result { + let start = self.at; + while self.peek().is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '+' | '.')) { + self.at += 1; + } + let text: String = self.chars[start..self.at].iter().collect(); + let plain = text.strip_prefix(['-', '+']).unwrap_or(&text); + // Rust also reads words such as inf and nan, which are not numbers here. + let n = if plain.starts_with(|c: char| c.is_ascii_digit() || c == '.') { text.parse::().ok() } else { None }; + match n { + Some(n) if n.is_finite() => Ok(Res::Number(n)), + _ => { + self.at = start; + Err(self.expected("a number")) + } + } + } + + /// The number that the `digits` hex digits at `at` write; `None` when they are not all there. + fn hex(&self, at: usize, digits: usize) -> Option { + let hex: String = self.chars.iter().skip(at).take(digits).collect(); + // `from_str_radix` also takes a sign, which an escape does not have. + let valid = hex.len() == digits && hex.chars().all(|c| c.is_ascii_hexdigit()); + u32::from_str_radix(&hex, 16).ok().filter(|_| valid) + } + + fn string(&mut self) -> Result { + let Some(quote) = self.peek() else { return Err(self.expected("a string")) }; + let start = self.at; + self.at += 1; + let mut s = String::new(); + loop { + let Some(c) = self.peek() else { + self.at = start; + return Err(Fault::Syntax(format!("the string at character {} has no closing quote", start + 1))); + }; + self.at += 1; + if c == quote { + return Ok(s); + } + if c != '\\' { + s.push(c); + continue; + } + let Some(e) = self.peek() else { continue }; + self.at += 1; + match e { + 'n' => s.push('\n'), + 't' => s.push('\t'), + 'r' => s.push('\r'), + 'b' => s.push('\u{8}'), + 'f' => s.push('\u{c}'), + 'v' => s.push('\u{b}'), + '0' => s.push('\0'), + '\n' => {} + 'u' | 'x' => { + let escape = self.at - 1; + let digits = if e == 'u' { 4 } else { 2 }; + let code = self.hex(self.at, digits); + // A high surrogate and the `\u` escape of a low one after it are one character. + let low = code.filter(|c| (0xD800..0xDC00).contains(c)).and_then(|_| { + let next = self.chars.get(self.at + digits..self.at + digits + 2)?; + (next == ['\\', 'u']).then(|| self.hex(self.at + digits + 2, 4)).flatten().filter(|c| (0xDC00..0xE000).contains(c)) + }); + let (code, len) = match (code, low) { + (Some(high), Some(low)) => (Some(0x10000 + ((high - 0xD800) << 10) + (low - 0xDC00)), digits + 6), + (code, _) => (code, digits), + }; + match code.and_then(char::from_u32) { + Some(c) => { + s.push(c); + self.at += len; + } + None => return Err(Fault::Syntax(format!("the escape at character {escape} is not valid"))), + } + } + e => s.push(e), + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn spec(class: &str, props: Vec<(&str, Res)>) -> Spec { + Spec { class: class.into(), props: props.into_iter().map(|(k, v)| (k.into(), v)).collect() } + } + + #[test] + fn a_resource_specification_reads_its_controls_and_values() { + let got = parse( + "p: Panel { text: 'Messages', alignChildren: ['right', \"top\"], \ + g: Group { st: StaticText { text: 'a\\'b' } } \ + e: EditText { properties: {multiline: true, name: null}, characters: -3.5e1, }, }", + ); + let want = spec( + "Panel", + vec![ + ("text", Res::String("Messages".into())), + ("alignChildren", Res::Array(vec![Res::String("right".into()), Res::String("top".into())])), + ("g", Res::Control(spec("Group", vec![("st", Res::Control(spec("StaticText", vec![("text", Res::String("a'b".into()))])))]))), + ( + "e", + Res::Control(spec( + "EditText", + vec![ + ("properties", Res::Object(vec![("multiline".into(), Res::Bool(true)), ("name".into(), Res::Null)])), + ("characters", Res::Number(-35.0)), + ], + )), + ), + ], + ); + assert_eq!(got, Ok(want)); + assert_eq!(parse(" dialog{} "), Ok(spec("dialog", vec![]))); + } + + #[test] + fn a_malformed_resource_specification_is_a_syntax_fault() { + for text in [ + "dialog", + "dialog {", + "dialog { b: }", + "dialog { b: Button { } } x", + "dialog { b Button {} }", + "dialog { t: 'open }", + "dialog { n: inf }", + "dialog { n: 1.2.3 }", + "dialog { a: [1 2] }", + "dialog { o: { b: Button {} } }", + "dialog { a: [Button {}] }", + "dialog { v: orange }", + "dialog { t: '\\u12' }", + "dialog { t: '\\x+A' }", + "dialog { t: '\\u+00A' }", + "{ }", + ] { + assert!(matches!(parse(text), Err(Fault::Syntax(_))), "{text}: {:?}", parse(text)); + } + assert_eq!(parse("dialog { t: '\\x0A\\u0041' }"), Ok(spec("dialog", vec![("t", Res::String("\nA".into()))]))); + } + + #[test] + fn a_surrogate_pair_of_escapes_is_one_character_and_a_lone_surrogate_is_a_syntax_fault() { + assert_eq!(parse("dialog { t: '\\uD83D\\uDE00!' }"), Ok(spec("dialog", vec![("t", Res::String("\u{1F600}!".into()))]))); + for text in ["dialog { t: '\\uD83D' }", "dialog { t: '\\uD83Dx' }", "dialog { t: '\\uD83D\\u0041' }", "dialog { t: '\\uDE00' }"] { + assert_eq!(parse(text), Err(Fault::Syntax("the escape at character 14 is not valid".into())), "{text}"); + } + } + + #[test] + fn a_resource_specification_that_ends_early_says_at_which_character() { + assert_eq!(parse("dialog {"), Err(Fault::Syntax("expected a name at character 9, the end of the resource specification".into()))); + assert_eq!(parse("dialog"), Err(Fault::Syntax("expected { after the type at character 7, the end of the resource specification".into()))); + } + + #[test] + fn a_resource_specification_past_the_limits_is_refused() { + let deep = format!("dialog {{ a: {}1{} }}", "[".repeat(MAX_NESTING), "]".repeat(MAX_NESTING)); + assert!(matches!(parse(&deep), Err(Fault::Limit(_))), "{:?}", parse(&deep)); + let fits = format!("dialog {{ a: {}1{} }}", "[".repeat(MAX_NESTING - 1), "]".repeat(MAX_NESTING - 1)); + assert!(parse(&fits).is_ok()); + let long = format!("dialog {{ t: '{}' }}", "x".repeat(MAX_BYTES)); + assert!(matches!(parse(&long), Err(Fault::Limit(_)))); + } +} diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs new file mode 100644 index 0000000000..95719bf965 --- /dev/null +++ b/crates/js/src/scriptui_tests.rs @@ -0,0 +1,1069 @@ +//! ScriptUI's `Window`: building a dialog, its description, the events a host gives `show()`, the +//! handlers they run, and the limits on what a dialog may hold. + +use std::cell::RefCell; +use std::collections::VecDeque; +use std::rc::Rc; + +use super::*; + +/// What the host was given: each description, and each `end`'s result and whether it was normal. +#[derive(Default)] +struct Seen { + descriptions: Vec, + ends: Vec<(f64, bool)>, +} + +/// The events `wait` has left to give. +type Queue = Rc>>; + +/// A realm whose `wait` gives the events in `events`, in order, and throws when none is left +/// (or waits, where the run can). +fn realm(events: Vec) -> (Realm, Rc>, Queue) { + let mut r = Realm::new(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + let seen: Rc> = Rc::default(); + let queue = Rc::new(RefCell::new(VecDeque::from(events))); + let can_wait = r.wait_flag(); + let s = seen.clone(); + let open: HostFunction = Rc::new(move |args| { + s.borrow_mut().descriptions.push(args.into_iter().next().unwrap_or(Data::Undefined)); + Ok(Data::Undefined) + }); + let s = seen.clone(); + let q = queue.clone(); + let wait: HostFunction = Rc::new(move |args| { + s.borrow_mut().descriptions.push(args.into_iter().next().unwrap_or(Data::Undefined)); + match q.borrow_mut().pop_front() { + Some(e) => Ok(e), + None if can_wait.get() => Err(HostError::Wait), + None => Err(HostError::Error("no event left".into())), + } + }); + let s = seen.clone(); + let end: HostFunction = Rc::new(move |args| { + let n = match args.first() { + Some(Data::Number(n)) => *n, + _ => f64::NAN, + }; + s.borrow_mut().ends.push((n, matches!(args.get(1), Some(Data::Bool(true))))); + Ok(Data::Undefined) + }); + let items = vec![("open".into(), HostItem::Function(open)), ("wait".into(), HostItem::Function(wait)), ("end".into(), HostItem::Function(end))]; + r.define_script_ui(items).unwrap(); + (r, seen, queue) +} + +fn click(id: usize) -> Data { + Data::Object(vec![("event".into(), Data::String("click".into())), ("id".into(), Data::Number(id as f64))]) +} + +fn change(id: usize, value: Data) -> Data { + Data::Object(vec![("event".into(), Data::String("change".into())), ("id".into(), Data::Number(id as f64)), ("value".into(), value)]) +} + +fn close() -> Data { + Data::Object(vec![("event".into(), Data::String("close".into()))]) +} + +fn field<'a>(d: &'a Data, name: &str) -> &'a Data { + match d { + Data::Object(fields) => fields.iter().find(|(k, _)| k == name).map_or(&Data::Undefined, |(_, v)| v), + _ => &Data::Undefined, + } +} + +fn nodes(d: &Data) -> Vec { + match field(d, "nodes") { + Data::Array(a) => a.clone(), + _ => Vec::new(), + } +} + +/// Every built control, in the order the description lists them: 0 is the dialog. +const FORM: &str = r#" + var w = new Window("dialog", "Form"); + var g = w.add("group"); + var label = g.add("statictext", undefined, "Name:"); + var name = g.add("edittext", undefined, "first"); + var p = w.add("panel", undefined, "Options"); + var check = p.add("checkbox", undefined, "Bold"); + var r1 = p.add("radiobutton", undefined, "A"); + var r2 = p.add("radiobutton", undefined, "B"); + var drop = p.add("dropdownlist", undefined, ["x", "y", "z"]); + var box = p.add("listbox", undefined, ["one", "two"]); + var slide = p.add("slider", undefined, 5, 0, 10); + var bar = p.add("progressbar", undefined, 3, 10); + var ok = w.add("button", undefined, "OK"); + var cancel = w.add("button", undefined, "Cancel", {name: "cancel"}); +"#; + +#[test] +fn a_dialog_with_each_control_gives_back_the_values_the_person_set() { + let events = vec![ + change(3, Data::String("second".into())), + click(5), + click(6), + click(7), + change(8, Data::Number(2.0)), + change(9, Data::Number(1.0)), + change(10, Data::Number(7.5)), + click(12), + ]; + let (mut r, seen, _) = realm(events); + let source = format!( + "{FORM} var result = w.show(); [result, name.text, check.value, r1.value, r2.value, drop.selection.text, box.selection.index, slide.value, bar.value].join('|')" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("1|second|true|false|true|z|1|7.5|3".into())); + let seen = seen.borrow(); + let first = nodes(&seen.descriptions[0]); + let kinds: Vec = first + .iter() + .map(|n| match field(n, "kind") { + Data::String(s) => s.clone(), + _ => String::new(), + }) + .collect(); + let want = [ + "dialog", + "group", + "statictext", + "edittext", + "panel", + "checkbox", + "radiobutton", + "radiobutton", + "dropdownlist", + "listbox", + "slider", + "progressbar", + "button", + "button", + ]; + assert_eq!(kinds, want); + assert_eq!(field(&first[3], "parent"), &Data::Number(1.0), "the field is in the group"); + assert_eq!(field(&first[8], "items"), &Data::Array(vec![Data::String("x".into()), Data::String("y".into()), Data::String("z".into())])); + assert_eq!(field(&first[10], "maxvalue"), &Data::Number(10.0)); + assert_eq!(field(&seen.descriptions[0], "defaultElement"), &Data::Number(12.0), "OK is the default element by its text"); + assert_eq!(field(&seen.descriptions[0], "cancelElement"), &Data::Number(13.0), "Cancel is the cancel element by its name"); + assert_eq!(seen.ends, vec![(1.0, true)]); +} + +#[test] +fn the_default_and_cancel_buttons_close_with_1_and_2_and_a_close_gives_0() { + for (event, want) in [(click(12), 1.0), (click(13), 2.0), (close(), 0.0)] { + let (mut r, _, _) = realm(vec![event]); + assert_eq!(r.run(&format!("{FORM} w.show()")).unwrap(), JsValue::Number(want)); + } +} + +#[test] +fn a_button_with_a_handler_does_not_close_the_dialog() { + let (mut r, _, _) = realm(vec![click(12), click(13)]); + let source = format!("{FORM} var clicks = 0; ok.onClick = function () {{ clicks++; }}; [w.show(), clicks].join()"); + assert_eq!(r.run(&source).unwrap(), JsValue::String("2,1".into())); +} + +#[test] +fn close_gives_its_result_and_on_close_can_keep_the_dialog_open() { + let (mut r, seen, _) = realm(vec![click(5), click(5)]); + let source = format!( + "{FORM} var asked = 0; check.onClick = function () {{ w.close(7); }}; w.onClose = function () {{ asked++; return asked > 1; }}; [w.show(), asked].join()" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("7,2".into())); + assert_eq!(seen.borrow().ends, vec![(7.0, true)]); +} + +#[test] +fn close_in_on_show_ends_show_without_waiting() { + let (mut r, seen, _) = realm(Vec::new()); + assert_eq!(r.run(&format!("{FORM} w.onShow = function () {{ w.close(4); }}; w.show()")).unwrap(), JsValue::Number(4.0)); + assert_eq!(seen.borrow().descriptions.len(), 1, "only open saw the dialog"); +} + +#[test] +fn handlers_change_other_controls_and_the_next_description_shows_it() { + let (mut r, seen, _) = realm(vec![click(5), click(12)]); + let source = + format!("{FORM} check.onClick = function () {{ name.text = check.value ? 'on' : 'off'; slide.enabled = false; }}; w.show(); name.text"); + assert_eq!(r.run(&source).unwrap(), JsValue::String("on".into())); + let seen = seen.borrow(); + let after = nodes(&seen.descriptions[2]); + assert_eq!(field(&after[3], "text"), &Data::String("on".into())); + assert_eq!(field(&after[10], "enabled"), &Data::Bool(false)); +} + +#[test] +fn on_change_runs_after_on_changing() { + let (mut r, _, _) = realm(vec![change(3, Data::String("x".into())), click(12)]); + let source = format!( + "{FORM} var log = []; name.onChanging = function () {{ log.push('changing ' + name.text); }}; name.onChange = function () {{ log.push('change'); }}; w.show(); log.join()" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("changing x,change".into())); +} + +#[test] +fn a_handler_that_loops_ends_the_run_at_its_fuel() { + let (mut r, seen, _) = realm(vec![click(5)]); + r.set_limits(Limits { fuel: 200_000, ..Limits::default() }); + let e = r.run(&format!("{FORM} check.onClick = function () {{ for (;;) {{}} }}; w.show()")).unwrap_err(); + assert!(matches!(e.kind, RunErrorKind::Limit(_)), "{e:?}"); + assert_eq!(seen.borrow().ends, vec![(0.0, false)], "show ended without its result"); +} + +#[test] +fn a_dialog_cannot_be_shown_inside_its_own_or_another_show() { + let (mut r, _, _) = realm(vec![click(5), click(12)]); + let source = format!( + "{FORM} var errors = []; check.onClick = function () {{ try {{ w.show(); }} catch (e) {{ errors.push(e.message); }} try {{ new Window('dialog').show(); }} catch (e) {{ errors.push(e.message); }} }}; w.show(); errors.join('|')" + ); + assert_eq!( + r.run(&source).unwrap(), + JsValue::String("show: this dialog is already showing|show: a dialog cannot open while another dialog is showing".into()) + ); +} + +#[test] +fn a_dialog_can_be_shown_again_after_it_closed() { + let (mut r, _, _) = realm(vec![click(12), click(13)]); + assert_eq!(r.run(&format!("{FORM} [w.show(), w.show()].join()")).unwrap(), JsValue::String("1,2".into())); +} + +#[test] +fn types_that_are_not_available_yet_throw_errors_that_say_so() { + for (source, want) in [ + ("new Window('palette')", "Window: a window of type palette is not available yet; use dialog"), + ("new Window('palette { b: Button {} }')", "Window: a window of type palette is not available yet; use dialog"), + ("new Window('dialog').add('p: TabbedPanel {}')", "add: the control type tabbedpanel is not available yet"), + ("new Window('dialog').add('tabbedpanel')", "add: the control type tabbedpanel is not available yet"), + ("new Window('dialog').add('wobble')", "add: there is no control type wobble"), + ("new Window('dialog').add('button').add('button')", "add: a button holds no controls"), + ( + "new Window('dialog').add('listbox', undefined, [], {multiselect: true})", + "add: a list box that selects several items is not available yet", + ), + ] { + let (mut r, _, _) = realm(Vec::new()); + let e = r.run(&format!("try {{ {source}; 'made' }} catch (e) {{ e.message }}")).unwrap(); + assert_eq!(e, JsValue::String(want.into()), "{source}"); + } +} + +/// A dialog built from a resource specification: 0 is the dialog, 1 the panel, 2 its group, 3 the +/// static text, 4 the edit field, 5 the button group, 6 OK and 7 Cancel. +const RESOURCE_FORM: &str = r#" + var w = new Window("dialog { text: 'Form', ignored: 1, \ + msg: Panel { orientation: 'column', alignChildren: ['right', 'top'], text: 'Messages', \ + title: Group { st: StaticText { text: 'Title:' }, et: EditText { text: 'Sample', characters: 35 } } \ + } \ + buttons: Group { \ + ok: Button { text: 'Build', properties: {name: 'ok'} }, \ + no: Button { text: 'Cancel', properties: {name: 'cancel'} } \ + } \ + }", "not read", [0, 0, 10, 10]); +"#; + +#[test] +fn a_resource_specification_builds_the_controls_it_names() { + let (mut r, seen, _) = realm(vec![change(4, Data::String("typed".into())), click(6)]); + let rest = r#" + var t = w.msg.title; + var shape = [w.text, w.bounds === undefined, w.children.length, w.msg.type, w.msg.text, w.msg.orientation, w.msg.alignChildren.join(), + t.parent === w.msg, t.st.type, t.st.text, t.et.type, t.et.characters, w.buttons.ok.name, w.buttons.no.name, w.ignored].join('|'); + var p = w.add("more: Panel { text: 'More', e: EditText { properties: {multiline: true}, text: 'x' }, l: DropDownList { properties: {items: ['a', 'b']} } }"); + var added = [p.parent === w, w.more === undefined, p.e.properties.multiline, p.l.items.length, p.l.items[1].text].join('|'); + p.parent.remove(p); + [shape, added, w.show(), t.et.text].join('#') + "#; + let source = format!("{RESOURCE_FORM} {rest}"); + assert_eq!( + r.run(&source).unwrap(), + JsValue::String( + "Form|true|2|panel|Messages|column|right,top|true|statictext|Title:|edittext|35|ok|cancel|1#true|true|true|2|b#1#typed".into() + ) + ); + let seen = seen.borrow(); + assert_eq!(nodes(&seen.descriptions[0]).len(), 8, "the dialog lists the controls the specification names"); +} + +#[test] +fn a_resource_slider_and_progress_bar_take_their_creation_properties_and_values() { + let (mut r, _, _) = realm(Vec::new()); + let source = "var w = new Window(\"dialog { \ + s: Slider { properties: {name: 'size'}, minvalue: 2, maxvalue: 20, value: 7 }, \ + p: ProgressBar { properties: {name: 'done', alignment: 'fill'}, maxvalue: 50, value: 5 } }\"); \ + [w.s.name, w.s.minvalue, w.s.maxvalue, w.s.value, w.findElement('size') === w.s, w.p.name, w.p.alignment, w.p.maxvalue, w.p.value].join('|')"; + assert_eq!(r.run(source).unwrap(), JsValue::String("size|2|20|7|true|done|fill|50|5".into())); +} + +#[test] +fn a_resource_list_s_items_are_the_items_the_dialog_shows() { + let (mut r, _, _) = realm(vec![change(1, Data::Number(2.0)), click(2)]); + let source = "var w = new Window(\"dialog { l: DropDownList { items: ['a', 'b', 'c'], selection: 1 }, ok: Button { text: 'OK' } }\"); \ + var before = [w.l.items.length, w.l.selection.text].join(); [before, w.show(), w.l.selection.text].join('|')"; + assert_eq!(r.run(source).unwrap(), JsValue::String("3,b|1|c".into())); + let (mut r, _, _) = realm(Vec::new()); + let both = + r.run("try { new Window(\"dialog { l: ListBox { items: ['a'], properties: {items: ['b']} } }\"); 'made' } catch (e) { e.name }").unwrap(); + assert_eq!(both, JsValue::String("TypeError".into()), "items given both ways"); + let object = r + .run("try { new Window(\"dialog { l: ListBox { items: {}, properties: {name: 'choices'} } }\"); 'made' } catch (e) { e.name + ': ' + e.message }") + .unwrap(); + assert_eq!(object, JsValue::String("TypeError: items: give a list's items as an array".into()), "an object is not item texts"); + let none = r + .run("var n = new Window(\"dialog { l: ListBox { items: null, properties: {name: 'choices'} } }\"); [n.l.items.length, n.l.name].join()") + .unwrap(); + assert_eq!(none, JsValue::String("0,choices".into())); +} + +#[test] +fn an_edit_field_s_and_a_static_text_s_characters_reach_the_description() { + let (mut r, seen, _) = realm(vec![close()]); + r.run("var w = new Window(\"dialog { e: EditText { text: 'Sample', characters: 35 }, s: StaticText { text: 'Hi' } }\"); w.show()").unwrap(); + let first = nodes(&seen.borrow().descriptions[0]); + assert_eq!(field(&first[1], "characters"), &Data::Number(35.0)); + assert_eq!(field(&first[2], "characters"), &Data::Undefined, "a control without characters gives none"); +} + +#[test] +fn a_malformed_resource_specification_throws_a_syntax_error() { + for source in [ + "new Window('dialog { b: Button { text: } }')", + "new Window('dialog { b: Button {} ')", + "new Window('dialog {} trailing')", + "new Window('dialog').add('g: Group { v: orange }')", + "new Window('dialog').add('g: Group { o: { b: Button {} } }')", + "new Window('dialog').add('g: Group')", + "new Window('main: Dialog')", + ] { + let (mut r, _, _) = realm(Vec::new()); + let e = r.run(&format!("try {{ {source}; 'made' }} catch (e) {{ e.name }}")).unwrap(); + assert_eq!(e, JsValue::String("SyntaxError".into()), "{source}"); + } + let (mut r, _, _) = realm(Vec::new()); + let unknown = r.run("try { new Window('dialog { b: Wobble {} }'); 'made' } catch (e) { e.message }").unwrap(); + assert_eq!(unknown, JsValue::String("add: there is no control type wobble".into())); +} + +#[test] +fn a_resource_specification_keeps_to_the_dialog_limits() { + let (mut r, _, _) = realm(Vec::new()); + let many = r + .run(&format!( + "var s = 'dialog {{'; for (var i = 0; i <= {}; i++) s += ' b' + i + ': Button {{}}'; s += ' }}'; \ + try {{ new Window(s); 'made' }} catch (e) {{ e.name }}", + scriptui::MAX_CONTROLS + )) + .unwrap(); + assert_eq!(many, JsValue::String("RangeError".into())); + let fits = r + .run(&format!( + "var s = 'dialog {{'; for (var i = 0; i < {}; i++) s += ' b' + i + ': Button {{}}'; s += ' }}'; new Window(s).children.length", + scriptui::MAX_CONTROLS + )) + .unwrap(); + assert_eq!(fits, JsValue::Number(scriptui::MAX_CONTROLS as f64)); + let added = r + .run(&format!( + "var w = new Window('dialog'); for (var i = 0; i < {}; i++) w.add('button'); \ + var e = ''; try {{ w.add('g: Group {{ a: Button {{}}, b: Button {{}} }}'); }} catch (x) {{ e = x.name; }} [e, w.children.length].join()", + scriptui::MAX_CONTROLS - 2 + )) + .unwrap(); + assert_eq!(added, JsValue::String(format!("RangeError,{}", scriptui::MAX_CONTROLS - 1)), "the group took a place before its second button"); + let kept = + r.run("var g = w.children[w.children.length - 1]; [g.type, g.children.length, g.a === g.children[0], g.b === undefined].join()").unwrap(); + assert_eq!(kept, JsValue::String("group,1,true,true".into()), "the first button stays in the group"); + let nested = |depth: usize| { + format!( + "var s = ''; for (var d = 0; d < {depth}; d++) s += 'g: Group {{ '; for (d = 0; d < {depth}; d++) s += '}} '; \ + try {{ var c = new Window('dialog {{ ' + s + '}}'); while (c.g) c = c.g; 'made ' + c.type }} catch (e) {{ e.name }}" + ) + }; + assert_eq!(r.run(&nested(scriptui::MAX_DEPTH)).unwrap(), JsValue::String("made group".into())); + assert_eq!(r.run(&nested(scriptui::MAX_DEPTH + 1)).unwrap(), JsValue::String("RangeError".into())); +} + +#[test] +fn too_many_controls_too_deep_a_nesting_and_too_long_a_text_are_refused() { + let (mut r, _, _) = realm(Vec::new()); + let many = + r.run("var w = new Window('dialog'); try { for (var i = 0; i < 100000; i++) w.add('button'); } catch (e) { [e.name, i].join() }").unwrap(); + assert_eq!(many, JsValue::String(format!("RangeError,{}", scriptui::MAX_CONTROLS))); + let deep = + r.run("var c = new Window('dialog'); try { for (var d = 0; d < 1000; d++) c = c.add('group'); } catch (e) { [e.name, d].join() }").unwrap(); + assert_eq!(deep, JsValue::String(format!("RangeError,{}", scriptui::MAX_DEPTH))); + let items = r.run("var l = new Window('dialog').add('dropdownlist'); try { for (var n = 0; n < 5000; n++) l.add('item', n); } catch (e) { [e.name, n].join() }").unwrap(); + assert_eq!(items, JsValue::String(format!("RangeError,{}", scriptui::MAX_ITEMS))); + let long = r + .run("var w = new Window('dialog'); w.add('statictext', undefined, new Array(20000).join('x')); try { w.show(); } catch (e) { e.message }") + .unwrap(); + assert_eq!(long, JsValue::String("show: a control's text is longer than 16 KiB".into())); +} + +#[test] +fn an_add_that_a_getter_or_a_conversion_reenters_keeps_to_the_limits() { + let (mut r, _, _) = realm(Vec::new()); + let controls = r + .run( + "var w = new Window('dialog'); for (var i = 0; i < 511; i++) w.add('button'); \ + var props = {}; Object.defineProperty(props, 'name', {get: function () { w.add('button'); return 'n'; }}); \ + var e = ''; try { w.add('button', undefined, 'x', props); } catch (x) { e = x.name; } [e, w.children.length].join()", + ) + .unwrap(); + assert_eq!(controls, JsValue::String(format!("RangeError,{}", scriptui::MAX_CONTROLS)), "the getter took the last place"); + let items = r + .run( + "var w = new Window('dialog'); var l = w.add('listbox'); for (var n = 0; n < 1023; n++) l.add('item', 'i'); \ + var t = {toString: function () { l.add('item', 'inner'); return 'outer'; }}; \ + var e = ''; try { l.add('item', t); } catch (x) { e = x.name; } [e, l.items.length].join()", + ) + .unwrap(); + assert_eq!(items, JsValue::String(format!("RangeError,{}", scriptui::MAX_ITEMS)), "the conversion took the last place"); +} + +#[test] +fn a_new_list_s_items_count_only_once_it_is_added_and_too_many_are_refused_unread() { + let (mut r, _, _) = realm(Vec::new()); + let failed = r + .run( + "var w = new Window('dialog'); var l = w.add('listbox'); for (var n = 0; n < 1022; n++) l.add('item', 'i'); \ + var bad = {toString: function () { throw new Error('no text'); }}; \ + var e = ''; try { w.add('dropdownlist', undefined, ['a', bad]); } catch (x) { e = x.message; } \ + l.add('item', 'y'); l.add('item', 'z'); [e, l.items.length, w.children.length].join()", + ) + .unwrap(); + assert_eq!(failed, JsValue::String(format!("no text,{},1", scriptui::MAX_ITEMS)), "the list that was not added took no places"); + let long = r + .run( + "var w = new Window('dialog'); var read = false; var a = new Array(5000); a[0] = {toString: function () { read = true; return 'x'; }}; \ + var e = ''; try { w.add('listbox', undefined, a); } catch (x) { e = x.name; } [e, read, w.children.length].join()", + ) + .unwrap(); + assert_eq!(long, JsValue::String("RangeError,false,0".into()), "an array longer than the limit is refused before its items are read"); +} + +#[test] +fn a_collection_while_a_bounds_or_margins_value_is_read_keeps_that_value() { + let (mut r, seen, _) = realm(vec![close()]); + let source = "function heavy(n) { return {valueOf: function () { var junk = []; for (var k = 0; k < 50000; k++) junk.push({}); return n; }}; } \ + var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); \ + Object.defineProperty(b, 'bounds', {get: function () { return {left: heavy(1), top: 2, right: 30, bottom: 40}; }}); \ + Object.defineProperty(w, 'margins', {get: function () { return [heavy(3), 4, 5, 6]; }}); \ + w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(0.0)); + let seen = seen.borrow(); + let first = nodes(&seen.descriptions[0]); + let numbers = |v: &[f64]| Data::Array(v.iter().map(|n| Data::Number(*n)).collect()); + assert_eq!(field(&first[1], "bounds"), &numbers(&[1.0, 2.0, 30.0, 40.0])); + assert_eq!(field(&first[0], "margins"), &numbers(&[3.0, 4.0, 5.0, 6.0])); +} + +#[test] +fn a_list_a_later_getter_changes_is_described_as_the_person_picks_from_it() { + let (mut r, seen, _) = realm(vec![change(1, Data::Number(0.0)), click(2)]); + let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['A']); var b = w.add('button', undefined, 'OK'); \ + var swapped = false; Object.defineProperty(b, 'text', {get: function () { if (!swapped) { swapped = true; l.removeAll(); l.add('item', 'B'); } return 'OK'; }}); \ + var picked = ''; l.onChange = function () { picked = l.selection.text; }; w.show(); picked"; + assert_eq!(r.run(source).unwrap(), JsValue::String("B".into())); + let seen = seen.borrow(); + assert_eq!( + field(&nodes(&seen.descriptions[0])[1], "items"), + &Data::Array(vec![Data::String("B".into())]), + "the description shows the list as it is" + ); + let (mut r, _, _) = realm(Vec::new()); + let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['A']); var b = w.add('button', undefined, 'OK'); \ + Object.defineProperty(b, 'text', {get: function () { l.removeAll(); l.add('item', 'B'); return 'OK'; }}); \ + try { w.show(); } catch (e) { e.message }"; + assert_eq!(r.run(source).unwrap(), JsValue::String("show: a list's items or a container's controls changed while the dialog was read".into())); +} + +#[test] +fn a_list_item_text_a_later_getter_changes_is_described_as_the_person_picks_from_it() { + let (mut r, seen, _) = realm(vec![change(1, Data::Number(0.0)), click(2)]); + let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['A']); var b = w.add('button', undefined, 'OK'); \ + var swapped = false; Object.defineProperty(b, 'text', {get: function () { if (!swapped) { swapped = true; l.items[0].text = 'B'; } return 'OK'; }}); \ + var picked = ''; l.onChange = function () { picked = l.selection.text; }; w.show(); picked"; + assert_eq!(r.run(source).unwrap(), JsValue::String("B".into())); + let seen = seen.borrow(); + assert_eq!( + field(&nodes(&seen.descriptions[0])[1], "items"), + &Data::Array(vec![Data::String("B".into())]), + "the description shows the text the item has" + ); + let (mut r, _, _) = realm(Vec::new()); + let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['A']); var b = w.add('button', undefined, 'OK'); var n = 0; \ + Object.defineProperty(b, 'text', {get: function () { l.items[0].text = 'T' + n++; return 'OK'; }}); \ + try { w.show(); } catch (e) { e.message }"; + assert_eq!(r.run(source).unwrap(), JsValue::String("show: a list's items or a container's controls changed while the dialog was read".into())); +} + +#[test] +fn a_control_a_later_getter_removes_is_not_in_the_description() { + let (mut r, seen, _) = realm(vec![click(1)]); + let source = "var w = new Window('dialog'); var ok = w.add('button', undefined, 'OK'); var b = w.add('button', undefined, 'Go'); \ + var gone = false; Object.defineProperty(b, 'text', {get: function () { if (!gone) { gone = true; w.remove(ok); } return 'Go'; }}); \ + var went = 0; b.onClick = function () { went++; w.close(5); }; ok.onClick = function () { went = -1; }; [w.show(), went].join()"; + assert_eq!(r.run(source).unwrap(), JsValue::String("5,1".into()), "the click at index 1 reaches Go, which the dialog still holds"); + let seen = seen.borrow(); + let first = nodes(&seen.descriptions[0]); + assert_eq!(first.len(), 2, "the removed OK button is not described"); + assert_eq!(field(&first[1], "text"), &Data::String("Go".into())); + let (mut r, _, _) = realm(Vec::new()); + let source = "var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); \ + Object.defineProperty(b, 'text', {get: function () { w.add('statictext', undefined, 'more'); return 'Go'; }}); \ + try { w.show(); } catch (e) { e.message }"; + assert_eq!(r.run(source).unwrap(), JsValue::String("show: a list's items or a container's controls changed while the dialog was read".into())); +} + +#[test] +fn a_list_s_initial_items_are_read_through_their_getters() { + let (mut r, seen, _) = realm(vec![close()]); + let source = "var a = ['x']; Object.defineProperty(a, 0, {get: function () { return 'A'; }}); \ + var w = new Window('dialog'); w.add('listbox', undefined, a); w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(0.0)); + let seen = seen.borrow(); + assert_eq!(field(&nodes(&seen.descriptions[0])[1], "items"), &Data::Array(vec![Data::String("A".into())])); +} + +#[test] +fn an_object_made_to_look_like_a_container_charges_nothing_to_the_dialog() { + let (mut r, _, _) = realm(Vec::new()); + let source = format!( + "var w = new Window('dialog'); var fake = {{__vcKind: 'group', __vcWindow: w, __vcDepth: 0, __vcKids: []}}; \ + fake.add = w.add; var e = ''; try {{ fake.add('button'); }} catch (x) {{ e = x.name; }} \ + var l = w.add('listbox'); var fl = {{__vcKind: 'listbox', __vcWindow: w, __vcItems: []}}; fl.add = l.add; \ + var f = ''; try {{ fl.add('item', 'A'); }} catch (x) {{ f = x.name; }} \ + for (var n = 1; n < {}; n++) w.add('statictext'); [e, f, w.children.length].join()", + scriptui::MAX_CONTROLS + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String(format!("TypeError,TypeError,{}", scriptui::MAX_CONTROLS))); +} + +#[test] +fn find_element_skips_a_control_a_name_getter_removes() { + let (mut r, _, _) = realm(Vec::new()); + let source = "function heavy() { var junk = []; for (var k = 0; k < 50000; k++) junk.push({}); } \ + var w = new Window('dialog'); var a = w.add('button'); var b = w.add('button', undefined, 'B', {name: 'b'}); \ + Object.defineProperty(a, 'name', {get: function () { w.remove(b); b = null; heavy(); return 'a'; }}); \ + String(w.findElement('b'))"; + assert_eq!(r.run(source).unwrap(), JsValue::String("null".into())); +} + +#[test] +fn a_close_that_on_close_asks_for_is_part_of_the_close_it_refuses() { + let (mut r, _, _) = realm(vec![close(), click(1)]); + let source = "var w = new Window('dialog'); w.add('button', undefined, 'OK'); var asked = 0; \ + w.onClose = function () { asked++; if (asked == 1) { w.close(7); return false; } }; [w.show(), asked].join()"; + assert_eq!(r.run(source).unwrap(), JsValue::String("1,2".into()), "the refused close waits for the click on OK"); +} + +#[test] +fn a_hidden_or_disabled_ok_button_is_not_the_default_found_by_its_text() { + let (mut r, seen, _) = realm(vec![close()]); + let source = "var w = new Window('dialog'); w.add('button', undefined, 'OK').enabled = false; w.add('button', undefined, 'OK').visible = false; \ + w.add('button', undefined, 'OK'); w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(0.0)); + assert_eq!(field(&seen.borrow().descriptions[0], "defaultElement"), &Data::Number(3.0), "the OK button that can be clicked is the default"); +} + +#[test] +fn an_ok_or_cancel_button_in_a_hidden_or_disabled_group_is_not_found_by_its_text() { + let (mut r, seen, _) = realm(vec![close()]); + let source = "var w = new Window('dialog'); var g = w.add('group'); g.add('button', undefined, 'OK'); g.add('button', undefined, 'Cancel'); \ + g.visible = false; var h = w.add('panel'); h.add('group').add('button', undefined, 'OK'); h.enabled = false; \ + w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel'); w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(0.0)); + let seen = seen.borrow(); + assert_eq!(field(&seen.descriptions[0], "defaultElement"), &Data::Number(7.0), "the OK button outside the groups is the default"); + assert_eq!(field(&seen.descriptions[0], "cancelElement"), &Data::Number(8.0), "the Cancel button outside the group is the cancel button"); +} + +#[test] +fn an_edit_field_that_hides_its_text_is_refused_when_shown() { + let (mut r, seen, _) = realm(Vec::new()); + let source = "var w = new Window('dialog'); w.add('edittext', undefined, 'secret', {noecho: true}); try { w.show(); } catch (e) { e.message }"; + assert_eq!(r.run(source).unwrap(), JsValue::String("show: an edit field that hides its text (noecho) is not available yet".into())); + assert!(seen.borrow().descriptions.is_empty(), "the dialog never opens"); +} + +#[test] +fn a_bounds_value_that_is_not_finite_is_refused_when_shown() { + let (mut r, _, _) = realm(Vec::new()); + let v = r.run("var w = new Window('dialog'); w.add('button', [0, 0, Infinity, 20]); try { w.show(); } catch (e) { e.name }").unwrap(); + assert_eq!(v, JsValue::String("RangeError".into())); +} + +#[test] +fn a_script_cannot_change_a_dialog_s_controls_behind_its_back() { + let (mut r, _, _) = realm(vec![click(1)]); + let source = "var w = new Window('dialog'); var b = w.add('button', undefined, 'OK'); \ + w.children.push(w); w.__vcKids = []; try { w.__vcKids.push(w); } catch (e) {} b.__vcKind = 'dialog'; w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(1.0)); +} + +#[test] +fn a_show_that_waits_resumes_with_the_host_s_answer() { + let (mut r, seen, queue) = realm(Vec::new()); + r.start(&format!("{FORM} check.onClick = function () {{ name.text = 'clicked'; }}; var n = w.show(); n + ':' + name.text")).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Paused); + assert!(r.waits(), "show waits at open's first wait"); + r.answer(click(5)).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Paused); + assert!(r.waits(), "show waits again after the handler"); + queue.borrow_mut().push_back(click(12)); + r.answer(click(5)).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::String("1:clicked".into()))); + assert_eq!(seen.borrow().ends, vec![(1.0, true)]); +} + +#[test] +fn findelement_items_and_selection_follow_the_list() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var g = w.add('group'); var d = g.add('dropdownlist', undefined, [], {name: 'pick'}); \ + d.add('item', 'a'); var b = d.add('item', 'b'); d.selection = 1; var s1 = d.selection.text; b.selected = false; \ + var s2 = d.selection; d.selection = 0; d.removeAll(); [w.findElement('pick') === d, s1, s2, d.selection, d.items.length, String(b)].join()", + ) + .unwrap(); + assert_eq!(v, JsValue::String("true,b,,,0,b".into())); +} + +#[test] +fn a_new_control_s_sizes_can_be_set_a_side_at_a_time_and_reach_the_description() { + let (mut r, seen, _) = realm(vec![click(1)]); + let source = "var w = new Window('dialog'); var b = w.add('button', undefined, 'OK'); \ + b.preferredSize.width = 100; b.minimumSize.height = 30; b.maximumSize.width = 90; w.size.height = 200; w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(1.0)); + let seen = seen.borrow(); + let first = nodes(&seen.descriptions[0]); + let numbers = |v: &[f64]| Data::Array(v.iter().map(|n| Data::Number(*n)).collect()); + assert_eq!(field(&first[1], "size"), &numbers(&[100.0, -1.0]), "the side left alone stays to the layout"); + assert_eq!(field(&first[1], "min"), &numbers(&[-1.0, 30.0])); + assert_eq!(field(&first[1], "max"), &numbers(&[90.0, -1.0])); + assert_eq!(field(&first[0], "size"), &numbers(&[-1.0, 200.0]), "size takes the place of preferredSize"); +} + +#[test] +fn listeners_run_in_the_capture_target_and_bubbling_phases_until_one_stops() { + let (mut r, _, _) = realm(vec![click(2)]); + let source = "var w = new Window('dialog'); var g = w.add('group'); var b = g.add('button', undefined, 'Go'); var log = []; \ + w.addEventListener('click', function (e) { log.push('capture ' + e.eventPhase); }, true); \ + b.onClick = function () { log.push('onClick'); }; \ + b.addEventListener('click', function (e) { log.push(e.type + ' ' + (e.target === b) + ' ' + (this === b)); }); \ + g.addEventListener('click', function (e) { log.push('group ' + (e.currentTarget === g)); }); \ + w.addEventListener('click', function () { log.push('dialog'); w.close(3); }); \ + [w.show(), log.join()].join('|')"; + assert_eq!(r.run(source).unwrap(), JsValue::String("3|capture 1,onClick,click true true,group true,dialog".into())); + let (mut r, _, _) = realm(vec![click(1), close(), click(1), close()]); + let source = "var w = new Window('dialog'); var b = w.add('button', undefined, 'OK'); var log = []; \ + function count() { log.push('count'); } b.addEventListener('click', count); b.addEventListener('click', count); \ + b.addEventListener('click', function (e) { e.stopPropagation(); }); \ + w.addEventListener('click', function () { log.push('dialog'); }); \ + w.addEventListener('show', function (e) { log.push('show ' + e.bubbles); }); \ + var first = w.show(); b.removeEventListener('click', count); var second = w.show(); [first, second, log.join()].join('|')"; + assert_eq!( + r.run(source).unwrap(), + JsValue::String("0|0|show false,count,show false".into()), + "a button with a click listener does not close the dialog by itself, and the same listener is added once" + ); + for (source, want) in [ + ("w.addEventListener('click', function () { w.close(3); })", "3"), + ("w.addEventListener('click', function () { w.close(3); }, true)", "3"), + ("w.addEventListener('click', function () {})", "1"), + ] { + let (mut r, _, _) = realm(vec![click(1)]); + let source = format!("var w = new Window('dialog'); w.add('button', undefined, 'OK'); {source}; String(w.show())"); + assert_eq!(r.run(&source).unwrap(), JsValue::String(want.into()), "a dialog listener's close(result) decides what show() gives: {source}"); + } + for (source, want) in [ + ("new Window('dialog').addEventListener('mouseover', function () {})", "Error addEventListener: the event mouseover is not available yet"), + ("new Window('dialog').addEventListener('wobble', function () {})", "Error addEventListener: there is no event wobble"), + ("new Window('dialog').addEventListener('click', 'code')", "TypeError addEventListener: give the handler as a function"), + ] { + let (mut r, _, _) = realm(Vec::new()); + let e = r.run(&format!("try {{ {source}; 'added' }} catch (e) {{ e.name + ' ' + e.message }}")).unwrap(); + assert_eq!(e, JsValue::String(want.into()), "{source}"); + } +} + +#[test] +fn an_event_on_objects_made_to_look_like_controls_ends_with_a_type_error() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var b = new Window('dialog').add('button', undefined, 'Go'); var ran = false; \ + var f = {__vcKind: 'button'}; var g = {__vcKind: 'group'}; f.__vcParent = g; g.__vcParent = f; f.onClick = function () { ran = true; }; \ + try { b.notify.call(f, 'onClick'); 'ran' } catch (e) { e.name + ' ' + ran }", + ) + .unwrap(); + assert_eq!(v, JsValue::String("TypeError false".into()), "a parent cycle ends at once, not when the run's fuel is gone"); +} + +#[test] +fn lists_find_and_remove_items_and_take_their_items_in_the_creation_properties() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var d = w.add('dropdownlist', undefined, undefined, {items: ['a', 'b', 'c']}); \ + var x = w.add('listbox', undefined, {items: ['x'], name: 'xs'}); \ + d.selection = 2; var b = d.find('b'); d.remove('b'); d.remove(0); d.remove('zzz'); d.remove(7); \ + [d.items.length, d.items[0].text, d.selection.text, b.index, d.find('q'), x.items[0].text, x.name].join()", + ) + .unwrap(); + assert_eq!(v, JsValue::String("1,c,c,-1,,x,xs".into())); + let both = r.run("try { new Window('dialog').add('listbox', undefined, ['a'], {items: ['b']}); 'made' } catch (e) { e.name }").unwrap(); + assert_eq!(both, JsValue::String("TypeError".into())); + let freed = r + .run( + "var w = new Window('dialog'); var l = w.add('listbox'); for (var n = 0; n < 1024; n++) l.add('item', 'i'); \ + l.remove(0); l.add('item', 'again'); var g = w.add('group'); g.add('button', undefined, 'A'); g.add('button', undefined, 'B'); \ + g.remove('A'); g.remove(g.children[0]); w.remove(l); var m = w.add('listbox'); \ + for (var k = 0; k < 1024; k++) m.add('item', 'j'); for (var i = 0; i < 510; i++) w.add('button'); \ + [g.children.length, w.children.length, m.items.length].join()", + ) + .unwrap(); + assert_eq!(freed, JsValue::String("0,512,1024".into()), "a removed item or control frees its place"); +} + +#[test] +fn a_group_takes_its_creation_properties_third() { + let (mut r, seen, _) = realm(vec![close()]); + let v = r + .run( + "var w = new Window('dialog'); var g = w.add('group', undefined, {orientation: 'column', alignChildren: 'left', name: 'g'}); \ + var p = w.add('panel', undefined, 'Title', {margins: 4}); w.show(); [g.orientation, g.alignChildren, g.name, g.text, p.text, p.margins].join()", + ) + .unwrap(); + assert_eq!(v, JsValue::String("column,left,g,,Title,4".into())); + let seen = seen.borrow(); + assert_eq!(field(&nodes(&seen.descriptions[0])[1], "orientation"), &Data::String("column".into())); +} + +#[test] +fn a_radio_button_turned_on_turns_off_the_others_of_its_set() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var r1 = w.add('radiobutton', undefined, 'A'); var r2 = w.add('radiobutton', undefined, 'B'); \ + var r3 = w.add('radiobutton', undefined, 'C'); w.add('statictext', undefined, 'Other'); var r4 = w.add('radiobutton', undefined, 'D'); \ + var c = w.add('checkbox', undefined, 'E'); var clicks = 0; r3.onClick = function () { clicks++; }; \ + r1.value = true; r2.value = true; var set = [r1.value, r2.value, r3.value]; r4.value = true; \ + r3.notify('onClick'); r3.notify(); c.notify('onClick'); \ + set.concat([r1.value, r2.value, r3.value, r4.value, c.value, clicks]).join()", + ) + .unwrap(); + assert_eq!( + v, + JsValue::String("false,true,false,false,false,true,true,true,2".into()), + "a radio button after another kind of control starts a new set" + ); +} + +#[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_remove_that_runs_out_of_fuel_leaves_the_dialog_as_it_was() { + let (mut r, _, _) = realm(Vec::new()); + r.run("var w = new Window('dialog'); var g = w.add('group'); for (var n = 0; n < 300; n++) g.add('button');").unwrap(); + let mut failed = 0; + for fuel in 1..20_000 { + r.set_limits(Limits { fuel, ..Limits::default() }); + if r.run("w.remove(g);").is_ok() { + break; + } + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + let state = r.run("[w.children.length, g.parent === w, g.window === w, g.children[299].window === w].join()").unwrap(); + // The run may end after remove returned, with the group already removed. + if state == JsValue::String("0,false,false,false".into()) { + break; + } + failed += 1; + assert_eq!(state, JsValue::String("1,true,true,true".into()), "a remove that ended at fuel {fuel} changed the dialog"); + } + assert!(failed > 300, "the runs ended inside remove's walk of the group ({failed})"); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + let v = r + .run( + "var added = 0; try { while (true) { w.add('button'); added++; } } catch (e) {} [w.children.length, g.parent, g.window, added].join('|')", + ) + .unwrap(); + assert_eq!(v, JsValue::String("512|||512".into()), "the removed group's controls are counted off the dialog once"); +} + +/// Runs `op` after `setup` with each heap limit from the bytes `setup` left up to past what `op` +/// adds, and after each run that ended at the limit, gives `check` the realm without a limit and +/// what its host was given. +fn at_each_heap_limit(setup: &str, op: &str, check: impl Fn(&mut Realm, &RefCell, u64)) { + let ready = || { + let (mut r, seen, _) = realm(vec![close(); 4]); + r.run(setup).unwrap(); + r.collect_garbage(); + (r, seen) + }; + let (mut r, _) = ready(); + let before = r.interp().heap.bytes; + r.run(op).unwrap(); + let added = r.interp().heap.bytes.saturating_sub(before) as u64; + let mut ended = 0; + for extra in 0..added + 64 { + let (mut r, seen) = ready(); + let limit = r.interp().heap.bytes + extra as usize; + r.set_limits(Limits { fuel: 10_000_000, heap_bytes: limit, ..Limits::default() }); + let e = match r.run(op) { + Ok(_) => break, + Err(e) => e, + }; + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{op} at {extra}: {e:?}"); + ended += 1; + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + check(&mut r, &seen, extra); + } + assert!(ended > 0, "{op} ended at the heap limit"); +} + +#[test] +fn an_add_or_a_remove_that_ends_at_the_heap_limit_leaves_the_dialog_as_it_was() { + let list = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['a', 'b', 'c']); l.selection = 2;"; + for op in ["w.add('button')", "l.add('item', 'd')", "l.remove(0)", "l.removeAll()"] { + let check = |r: &mut Realm, seen: &RefCell, extra: u64| { + // What the script reads, and what `show()` describes from the dialog's own arrays. + let read = r.run("var d = []; for (var k = 0; k < l.items.length; k++) d.push(l.items[k].text); [w.children.length, d.join(' '), l.selection.index].join()"); + assert_eq!(read, Ok(JsValue::String("1,a b c,2".into())), "{op} ended at {extra} bytes and changed what the script reads"); + let at = seen.borrow().descriptions.len(); + r.run("w.show()").unwrap(); + let shown = nodes(&seen.borrow().descriptions[at]); + let items = Data::Array(["a", "b", "c"].iter().map(|t| Data::String((*t).into())).collect()); + assert_eq!( + (shown.len(), field(&shown[1], "items"), field(&shown[1], "selection")), + (2, &items, &Data::Number(2.0)), + "{op} ended at {extra} bytes and changed the dialog" + ); + }; + at_each_heap_limit(list, op, check); + } + // A removeAll that ends at the limit leaves the dialog's count of items as it was, so a full + // dialog takes no more items. + let full = + format!("var w = new Window('dialog'); var l = w.add('listbox', undefined, new Array({}).join('x,').split(','));", scriptui::MAX_ITEMS); + at_each_heap_limit(&full, "l.removeAll()", |r, _, extra| { + let more = r.run("try { l.add('item', 'y'); 'added' } catch (e) { e.name }"); + assert_eq!(more, Ok(JsValue::String("RangeError".into())), "removeAll ended at {extra} bytes and miscounted the items"); + }); +} + +#[test] +fn a_text_getter_that_changes_a_list_while_remove_looks_it_up_makes_remove_throw() { + let (mut r, _, _) = realm(Vec::new()); + 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())); +} + +#[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_listener_removed_and_added_again_in_the_same_event_does_not_run_in_it() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var b = w.add('button'); var ran = []; var once = true; function second() { ran.push(2); } \ + b.addEventListener('click', function () { ran.push(1); if (once) { once = false; b.removeEventListener('click', second); b.addEventListener('click', second); } }); \ + b.addEventListener('click', second); b.notify('onClick'); b.notify('onClick'); ran.join(',')", + ) + .unwrap(); + assert_eq!(v, JsValue::String("1,1,2".into()), "the second registration runs from the next event on"); +} + +#[test] +fn a_listener_a_capturing_container_registers_again_does_not_run_in_the_same_event() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var b = w.add('button'); var ran = []; var once = true; function own() { ran.push(2); } \ + w.addEventListener('click', function () { ran.push(1); if (once) { once = false; b.removeEventListener('click', own); b.addEventListener('click', own); } }, true); \ + b.addEventListener('click', own); b.notify('onClick'); b.notify('onClick'); ran.join(',')", + ) + .unwrap(); + assert_eq!(v, JsValue::String("1,1,2".into()), "the new registration runs from the next event on"); +} + +#[test] +fn a_close_a_getter_asks_for_while_the_dialog_is_read_again_ends_show() { + let (mut r, seen, _) = realm(vec![click(1)]); + let source = "var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); var armed = false; \ + b.onClick = function () { armed = true; }; \ + Object.defineProperty(b, 'text', {get: function () { if (armed) { armed = false; w.close(7); } return 'Go'; }}); w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(7.0)); + assert_eq!(seen.borrow().ends, vec![(7.0, true)]); +} + +#[test] +fn a_list_replaced_with_the_same_texts_is_described_with_a_new_revision() { + let (mut r, seen, _) = realm(vec![click(2), close()]); + let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['a', 'b']); var go = w.add('button', undefined, 'Go'); \ + go.onClick = function () { l.remove(1); l.add('item', 'b'); }; w.show()"; + r.run(source).unwrap(); + let seen = seen.borrow(); + let revision = |at: usize| field(&nodes(&seen.descriptions[at])[1], "itemsRevision").clone(); + // `open` and the first `wait` see the dialog as the person does; the second `wait` sees it after the handler. + assert_eq!(field(&nodes(&seen.descriptions[2])[1], "items"), field(&nodes(&seen.descriptions[1])[1], "items"), "the same texts"); + assert_ne!(revision(1), revision(2), "a replacement item is not the one the person saw"); +} + +#[test] +fn a_selection_a_later_getter_changes_is_described_as_it_is() { + let (mut r, seen, _) = realm(vec![click(2)]); + let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['A', 'B']); var b = w.add('button', undefined, 'OK'); \ + var moved = false; Object.defineProperty(b, 'text', {get: function () { if (!moved) { moved = true; l.selection = 1; } return 'OK'; }}); w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(1.0)); + assert_eq!(field(&nodes(&seen.borrow().descriptions[0])[1], "selection"), &Data::Number(1.0), "the description shows the selection as it is"); + let (mut r, _, _) = realm(Vec::new()); + let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['A', 'B']); var b = w.add('button', undefined, 'OK'); \ + var reads = 0; Object.defineProperty(b, 'text', {get: function () { reads++; l.selection = reads % 2; return 'OK'; }}); \ + try { w.show(); } catch (e) { e.message }"; + assert_eq!(r.run(source).unwrap(), JsValue::String("show: a list's items or a container's controls changed while the dialog was read".into())); +} + +#[test] +fn a_script_cannot_put_its_own_listener_list_on_a_control() { + let (mut r, _, _) = realm(Vec::new()); + 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/control.rs b/crates/ui-egui/src/control.rs index b550182214..c0c6bd0bc6 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1448,6 +1448,10 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val { return wrap(r); } + // A script's ScriptUI dialog gives the script an event and stays open. + if let Some(r) = crate::dialogs::script_window::dialog_method(app, method, ¶ms) { + return wrap(r); + } // `ui.dialog.set {action}` answers the dialog after setting its fields: the app's own key, which the // framework's method does not take. let action = if method == "ui.dialog.set" { params.as_object_mut().and_then(|o| o.remove("action")) } else { None }; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4ee61440a0..65b70a9a80 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -139,6 +139,7 @@ pub(crate) mod saved_names; pub(crate) mod screen_formats; pub mod script_check; pub mod script_run; +pub mod script_window; pub mod shape_builder_options; pub(crate) mod shapes; pub mod shortcut_import; diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 4804675d8d..131fb25611 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -1,6 +1,7 @@ //! File › Scripts › Other Script…: choosing a JavaScript file and the warning before it runs //! (`script.run` runs it), the question a run that keeps adding art asks, the question quitting //! asks while a script runs, and the dialogs a script opens with `alert`, `confirm` and `prompt`. +//! A script's ScriptUI dialog is in [`script_window`]; these questions and dialogs open over it. //! //! `ui.runScript {path? | source?, name?}` shows the warning for that script; without either it //! asks for a `.js` or `.jsx` file through the app's file asks. With Preferences › General › Show @@ -50,6 +51,7 @@ use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog}; +use super::script_window::{self, ScriptWindow}; use crate::VectorcraftApp; use crate::file_asks::{self, Owner}; @@ -435,6 +437,25 @@ pub(crate) fn busy(app: &VectorcraftApp) -> bool { app.any_dialog_open() || with_host(app, |host, _| !host.is_empty()).unwrap_or(false) } +/// Whether the run's question can open now: over nothing, or over the script's ScriptUI dialog +/// while nothing, neither a dialog nor a popup, is open over it. +pub(crate) fn can_ask(app: &VectorcraftApp) -> bool { + !busy(app) || script_window::uncovered(app) +} + +/// Opens `dialog` over the script's ScriptUI dialog when that is the top dialog, so the ScriptUI +/// dialog keeps its queued events and typed text under it; otherwise over nothing. +fn open_over_window(app: &VectorcraftApp, dialog: D) { + with_host(app, |host, _| match host.get::().map(StackDialog::id).filter(|id| host.stack().is_top(*id)) { + Some(parent) => { + host.open_child(dialog, parent); + } + None => { + host.open(dialog); + } + }); +} + /// Closes the open `D` the run no longer waits at, and drops its result: only answers the person /// or automation gave reach [`pump`]. A quit question asked over it stays, now over nothing, so /// its Cancel does not show the dialog again. @@ -519,34 +540,41 @@ fn close_question() -> CloseQuestion { ) } -/// Asks whether to continue a run that has added a great deal; Stop is its Cancel button. +/// Asks whether to continue a run that has added a great deal; Stop is its Cancel button. Over the +/// script's ScriptUI dialog, Continue shows that dialog again with its queued events and typed +/// text. pub(crate) fn open_growth(app: &VectorcraftApp) { - with_host(app, |host, _| host.open(growth_question())); + open_over_window(app, growth_question()); } /// Shows the dialog the running script waits at. pub(crate) fn open_notice(app: &VectorcraftApp, d: &ScriptDialog) { - with_host(app, |host, _| host.open(ScriptNotice::new(d))); + open_over_window(app, ScriptNotice::new(d)); } /// Shows the file dialog the running script waits at. pub(crate) fn open_picker(app: &VectorcraftApp, p: ScriptPicker) { - with_host(app, |host, _| host.open(ScriptFiles::new(p))); + open_over_window(app, ScriptFiles::new(p)); } /// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which -/// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet. +/// Cancel shows again as it was, with the events a ScriptUI dialog has not given the script yet and +/// the text typed in its fields. Any other open dialog stays, and quitting asks nothing yet. pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { with_host(app, |host, _| { - let own = host.get::().map(StackDialog::id).or_else(|| host.get::().map(StackDialog::id)); - match own { - Some(parent) if host.stack().is_top(parent) => { + let own = [ + host.get::().map(StackDialog::id), + host.get::().map(StackDialog::id), + host.get::().map(StackDialog::id), + ]; + match own.into_iter().flatten().find(|id| host.stack().is_top(*id)) { + Some(parent) => { host.open_child(close_question(), parent); } None if host.is_empty() => { host.open(close_question()); } - _ => {} + None => {} } }); } @@ -606,6 +634,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { if with_host(app, |host, _| host.get_mut::().is_some_and(|d| std::mem::take(&mut d.choose))).unwrap_or(false) { choose(app); } + script_window::pump(app); } /// Takes the answer to the quit question given between two queued runs, before the next run @@ -636,6 +665,7 @@ fn answer_close(app: &mut VectorcraftApp, close: Option(app); forget::(app); + forget::(app); app.sync_views(); } } diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs new file mode 100644 index 0000000000..a2ca70446d --- /dev/null +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -0,0 +1,859 @@ +//! A dialog a script builds with ScriptUI's `new Window("dialog")` and shows with `show()` +//! (kind `scriptWindow`). It draws the controls the running script's dialog holds, at the places +//! the engine laid them out, and gives the script each click and change. +//! +//! Its fields are `title` and, for `ui.dialog.set` and `ui.dialog.confirm`, `event` (`click`, +//! `change` or `close`), `control` (a control's index in the dialog's list of elements, or its +//! name or text) and `value` (an edit field's text, a slider's number, or a list's item index or +//! null). `ui.dialog.confirm` gives the script that event and leaves the dialog open, giving the +//! text still typed in its fields first when the event is a click or a close; an event the dialog +//! cannot take is an error. An edit field gives its text when it loses the keyboard focus, when +//! Enter is pressed in a one-line field, or before a click on another control or a close. Events +//! given in one frame reach the script one at a time, in order. Enter outside a field clicks the +//! default button, and Escape or `ui.dialog.cancel` clicks the cancel button, or closes the dialog +//! when it has none. Stop ends the run and puts back everything it did. +//! +//! The dialog lives on the window's dialog host. Its body has no app, so it keeps what the person +//! did and [`pump`] gives it to the run, and [`sync`] pushes the dialog the run waits at into it. + +use std::collections::{BTreeMap, VecDeque}; + +use craft::automation::protocol::Params; +use craft::behavior::{Selection, SelectionChange, keyed}; +use craft::theme::Variant; +use craft::ui::buttons::Button; +use craft::ui::choice::{Checkbox, Radio, RadioGroup}; +use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, RowHeight, Scroll, Show as _, ShowCollection as _, ShowContainer as _, clicked}; +use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; +use craft::ui::display::{Progress, Text}; +use craft::ui::layout_components::Stack; +use craft::ui::list::{List, ListRow}; +use craft::ui::pickers::Select; +use craft::ui::runtime::env::Env; +use craft::ui::runtime::focus::Initial; +use craft::ui::runtime::keys::take_submit; +use craft::ui::runtime::overlay; +use craft::ui::sections::{DialogRole, FooterButton, GroupBox}; +use craft::ui::style::StyleCx; +use craft::ui::text::TextField; +use craft::ui::value_drag::Slider; +use egui::Ui; +use serde_json::{Value, json}; +use vectorcraft_engine::script::dialogs::{cut_to, shown_text}; +use vectorcraft_engine::script::scriptui::{MAX_TEXT_BYTES, UiNode, check_event, list_index}; +use vectorcraft_engine::script::{ScriptUiDialog, UiEvent, UiKind, UiValue}; + +use super::script_run::with_host; +use crate::VectorcraftApp; + +/// The dialog kind of a script's ScriptUI dialog. +pub const KIND: &str = "scriptWindow"; + +/// The most of the dialog's content shown at once; a larger dialog scrolls. +const MAX_SHOWN: egui::Vec2 = egui::vec2(960.0, 640.0); + +/// The room the engine's layout adds around a list box's rows. +const LIST_PAD: f32 = 6.0; + +/// How many rows `row` tall a list box `height` tall shows; it scrolls the rest, inside the +/// dialog's own scroll. +fn list_rows(height: f32, row: f32) -> u16 { + let rows = ((height - LIST_PAD) / row).floor(); + if rows.is_finite() { rows.clamp(1.0, f32::from(u16::MAX)) as u16 } else { 1 } +} + +/// An event the script has not had yet, with its control by its id ([`UiNode::id`]), which stays +/// with the control while a handler adds or removes controls before it. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Queued { + Click(u64), + /// A change, and for a list's, the list's items as the person saw them and how many times the + /// script had replaced them. + Change(u64, UiValue, Option<(Vec, u64)>), + Close, + /// Escape or `ui.dialog.cancel` while a handler ran: the click on the cancel button of the + /// dialog the run waits at next, or its close box. + Cancel, +} + +/// The ScriptUI dialog on the window's dialog host; at most one is open. +pub(crate) struct ScriptWindow { + /// The dialog the run waits at, or while one of its handlers runs, the one it last waited at. + window: ScriptUiDialog, + /// The run waits at the dialog; while a handler runs, every control is disabled. + waiting: bool, + /// The text typed in each edit field that the script has not had yet, by the field's id. + drafts: BTreeMap, + /// The events the person gave that the script has not had yet; the script takes one each time + /// it waits. + queue: VecDeque, + /// The event `ui.dialog.set` set: `event`, `control` and `value`. + event: Option, + control: Option, + value: Option, + open: bool, + /// Stop was clicked. + stop: bool, + /// Escape or the close box asked for the dialog's cancel. + cancel: bool, + /// An error for the status bar. + status: Option, + /// The overlay layer the dialog's body was last drawn in. + layer: Option, +} + +impl ScriptWindow { + fn new(window: ScriptUiDialog) -> Self { + ScriptWindow { + window, + waiting: true, + drafts: BTreeMap::new(), + queue: VecDeque::new(), + event: None, + control: None, + value: None, + open: true, + stop: false, + cancel: false, + status: None, + layer: None, + } + } + + /// Which `show()` of the run the dialog is for. + pub(crate) fn shown(&self) -> u64 { + self.window.shown + } + + /// The text typed in edit field `i` that the script has not had yet. + #[cfg(test)] + pub(crate) fn typed(&self, i: usize) -> Option<&str> { + self.window.nodes.get(i).and_then(|n| self.drafts.get(&n.id)).map(String::as_str) + } + + /// Types `text` in edit field `i`, as the person does before the field loses the focus. + #[cfg(test)] + pub(crate) fn type_text(&mut self, i: usize, text: &str) { + if let Some(n) = self.window.nodes.get(i) { + self.drafts.insert(n.id, text.to_string()); + } + } + + /// The events the script has not had yet. + #[cfg(test)] + pub(crate) fn queued(&self) -> &VecDeque { + &self.queue + } + + /// Adds `event` after the events the script has not had yet. + pub(crate) fn queue(&mut self, event: &UiEvent) { + if let Some(q) = queued(&self.window, event) { + self.queue.push_back(q); + } + } + + /// The dialog the run waits at now (`None` while one of its handlers runs). A typed text whose + /// field the dialog no longer has is dropped. + fn sync(&mut self, waiting: Option) { + self.waiting = waiting.is_some(); + if let Some(w) = waiting { + self.window = w; + let fields: Vec = self.window.nodes.iter().skip(1).filter(|n| n.kind == UiKind::EditText).map(|n| n.id).collect(); + self.drafts.retain(|id, _| fields.contains(id)); + } + } + + /// Before a click or a close, gives the script the text typed in each edit field that has not + /// left the field yet, so the handler of a button that closes the dialog, or `onClose`, reads + /// it. A disabled or hidden field keeps its text for later. Each text is checked as the script + /// in `w` would check it first; when one is refused, every field keeps its text, `events` stays + /// as it was and the error is returned. + pub(crate) fn commit_drafts(&mut self, w: &ScriptUiDialog, events: &mut Vec) -> Result<(), String> { + let mut given = Vec::new(); + let mut changes = Vec::new(); + for (i, n) in w.nodes.iter().enumerate() { + if n.kind != UiKind::EditText + || n.readonly + || !n.enabled + || !n.visible + || events.iter().any(|e| matches!(e, UiEvent::Change(c, _) if *c == i)) + { + continue; + } + if let Some(text) = self.drafts.get(&n.id) { + if *text != n.text { + changes.push(check_event(w, UiEvent::Change(i, UiValue::Text(text.clone())))?); + } + given.push(n.id); + } + } + for id in given { + self.drafts.remove(&id); + } + let closing = |e: &UiEvent| matches!(e, UiEvent::Click(_) | UiEvent::Close); + events.sort_by_key(closing); + let at = events.iter().position(closing).unwrap_or(events.len()); + events.splice(at..at, changes); + Ok(()) + } + + /// Takes out of `events` each text an edit field gave as it lost the focus that the script + /// would refuse, and puts it back in its field, so the person can fix it. → the error of the + /// last one. + pub(crate) fn keep_refused_texts(&mut self, events: &mut Vec) -> Option { + let mut refused = None; + let (w, drafts) = (&self.window, &mut self.drafts); + events.retain(|e| { + let UiEvent::Change(i, UiValue::Text(text)) = e else { return true }; + match check_event(w, e.clone()) { + Ok(_) => true, + Err(error) => { + if let Some(n) = w.nodes.get(*i) { + drafts.insert(n.id, text.clone()); + } + refused = Some(error); + false + } + } + }); + refused + } + + /// The next queued event the dialog `w` can still take, with its control's index in `w` now. + /// An event whose control or list items a handler removed since it was given is dropped. + fn next_event(&mut self, w: &ScriptUiDialog) -> Option { + while let Some(next) = self.queue.pop_front() { + if let Some(event) = resolved(w, next) { + return Some(event); + } + } + None + } + + /// The events the person gave in this pass, after the ones before them: the typed texts the + /// script would refuse go back in their fields, and a click gives the typed texts first, or + /// waits while one of them is refused. + fn take_events(&mut self, mut events: Vec) { + if let Some(e) = self.keep_refused_texts(&mut events) { + self.status = Some(e); + } + if events.iter().any(|e| matches!(e, UiEvent::Click(_))) { + let w = self.window.clone(); + if let Err(e) = self.commit_drafts(&w, &mut events) { + // A refused text stays in its field, and the click waits for the person to fix it. + events.retain(|e| !matches!(e, UiEvent::Click(_))); + self.status = Some(e); + } + } + for e in &events { + self.queue(e); + } + } +} + +/// `event` in the dialog `w`, with its control by its id. +fn queued(w: &ScriptUiDialog, event: &UiEvent) -> Option { + let id = |i: usize| w.nodes.get(i).map(|n| n.id); + Some(match event { + UiEvent::Click(i) => Queued::Click(id(*i)?), + UiEvent::Change(i, v) => { + let items = matches!(v, UiValue::Index(_)).then(|| w.nodes.get(*i).map(|n| (n.items.clone(), n.items_revision))).flatten(); + Queued::Change(id(*i)?, v.clone(), items) + } + UiEvent::Close => Queued::Close, + }) +} + +/// The queued event `q` in the dialog `w`, with `control` the index its control has in `w` now. +/// `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 resolved(w: &ScriptUiDialog, q: Queued) -> Option { + match q { + Queued::Click(id) => Some(UiEvent::Click(index_of(w, id)?)), + Queued::Change(id, v, items) => { + let i = index_of(w, id)?; + if items.is_some_and(|(items, revision)| items != w.nodes[i].items || revision != w.nodes[i].items_revision) { + return None; + } + Some(UiEvent::Change(i, v)) + } + Queued::Close => Some(UiEvent::Close), + Queued::Cancel => Some(cancel_event(w)), + } +} + +/// The dialog `w`'s cancel: a click on its cancel button, or its close box when it has none or the +/// button cannot be clicked. +fn cancel_event(w: &ScriptUiDialog) -> UiEvent { + w.cancel_element.map(UiEvent::Click).filter(|e| check_event(w, e.clone()).is_ok()).unwrap_or(UiEvent::Close) +} + +/// The index of the control whose id ([`UiNode::id`]) is `id` in the dialog `w`, if it has one. +fn index_of(w: &ScriptUiDialog, id: u64) -> Option { + w.nodes.iter().position(|n| n.id == id).filter(|i| *i > 0) +} + +impl StackDialog for ScriptWindow { + type Result = (); + + fn id(&self) -> DialogId { + dialog_id(KIND) + } + + fn key(&self) -> Option<&str> { + Some(KIND) + } + + fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option> { + let top = stack.is_top(self.id()); + let heading = match self.window.title() { + "" => tl!("Script Alert").to_string(), + title => shown_text(title, false), + }; + let buttons = [FooterButton::new(tl!("Stop"), DialogRole::Other).stays_open(true)]; + let ScriptWindow { window, waiting, drafts, open, .. } = self; + let (window, waiting, drafts) = (&*window, *waiting, &*drafts); + // The dialog opens with the focus on its default button, so Enter clicks it until the + // person moves the focus into a field; without one that can be clicked, on its first control. + let focus_default = window.default_element.and_then(|i| window.nodes.get(i)).is_some_and(|n| n.visible && n.enabled); + let initial = if focus_default { Initial::Default } else { Initial::First }; + let dialog = Dialog::new(heading).buttons(buttons).initial_focus(initial).opened(Bind::bound(open)); + // The body can run twice in a pass (measure, then paint), so it only reports what the + // person did; the dialog applies the last run's report after the container. + let shown = dialog.show(ui, |ui, _| { + let (width, height) = window.size(); + let size = egui::vec2(width.max(1.0), height.max(1.0)); + let mut pass = Pass { layer: overlay::drawing_parent(ui.ctx()), ..Pass::default() }; + ui.scope(|ui| { + ui.set_max_size(MAX_SHOWN); + Stack::new().scroll(Scroll::both()).show(ui, |ui, _| { + let origin = ui.cursor().min; + ui.set_min_size(size); + // Each container comes before the controls it holds. + let mut containers: Vec> = vec![None; window.nodes.len()]; + for (i, n) in window.nodes.iter().enumerate().skip(1) { + if !n.visible { + continue; + } + let parent = containers.get(n.parent).copied().flatten(); + let place = Place { origin, enabled: waiting && n.enabled, default: window.default_element == Some(i), parent }; + let shown = control(ui, drafts, &place, (i, n, prompt_of(window, i))); + if let Some(slot) = containers.get_mut(i) { + *slot = shown.container; + } + pass.typing |= shown.typing; + pass.events.extend(shown.event); + pass.drafts.extend(shown.draft.map(|d| (n.id, d))); + } + }); + }); + pass + }); + let pass = shown.inner.unwrap_or_default(); + if pass.layer.is_some() { + self.layer = pass.layer; + } + for (id, draft) in pass.drafts { + match draft { + Some(text) => self.drafts.insert(id, text), + None => self.drafts.remove(&id), + }; + } + let (mut events, typing) = (pass.events, pass.typing); + // An Enter the focused control left untaken (a slider, a check box, a button) is the + // dialog's, unless a question is open over it or a field has the focus. + let submit = top && !typing && take_submit(ui.ctx()); + if shown.output.picked == Some(0) { + self.stop = true; + return None; + } + // Escape and the close box click the cancel button: the dialog stays open until the script + // closes it. + if shown.output.closed.is_some() { + self.open = true; + self.cancel = true; + return None; + } + // Enter in a field belongs to the field; with the focus on any other control, it clicks the + // default button. + if events.is_empty() && self.waiting && submit { + events.extend(self.window.default_element.map(UiEvent::Click)); + } + if !events.is_empty() { + self.take_events(events); + } + None + } + + fn json_fields(&self) -> Option { + Some(json!({ + "title": self.window.title(), + "event": self.event, + "control": self.control, + "value": self.value, + })) + } + + fn set_json_field(&mut self, _: &egui::Context, field: &str, value: Value) -> Result<(), String> { + match field { + "event" => { + let event = match &value { + Value::Null => None, + Value::String(e) if matches!(e.as_str(), "click" | "change" | "close") => Some(e.clone()), + _ => return Err("`event` must be click, change or close".into()), + }; + self.event = event; + } + "control" => { + if !matches!(value, Value::Null | Value::Number(_) | Value::String(_)) { + return Err("`control` must be a control's index, name or text".into()); + } + self.control = Some(value).filter(|v| !v.is_null()); + } + "value" => self.value = Some(value), + "title" => return Err(FieldRefusal::ReadOnly.message(field)), + _ => return Err(FieldRefusal::Unknown.message(field)), + } + Ok(()) + } +} + +/// Where a control is drawn: from `origin`, enabled or not, whether it is the default button, and +/// the accessibility node of the group or panel that holds it. +struct Place { + origin: egui::Pos2, + enabled: bool, + default: bool, + parent: Option, +} + +/// What drawing a control gave: the event it gives, whether an edit field has the keyboard focus, +/// a group's or a panel's accessibility node, and an edit field's typed text to keep (`Some`) or +/// forget (`None`). +#[derive(Default)] +struct Shown { + event: Option, + typing: bool, + container: Option, + draft: Option>, +} + +/// What one run of the dialog's body gave: the events, whether an edit field has the keyboard +/// focus, the typed texts to keep or forget, by field id, and the overlay layer it was drawn in. +#[derive(Default)] +struct Pass { + events: Vec, + typing: bool, + drafts: Vec<(u64, Option)>, + layer: Option, +} + +/// The text of the visible static text just before control `i` in its container: the visible +/// prompt of an edit field, a list box or a drop-down list, which screen readers call one without a +/// name by. Empty when there is none. +pub(crate) fn prompt_of(w: &ScriptUiDialog, i: usize) -> &str { + let Some(parent) = w.nodes.get(i).map(|n| n.parent) else { return "" }; + match w.nodes[..i].iter().skip(1).rev().find(|n| n.parent == parent && n.visible) { + Some(n) if n.kind == UiKind::StaticText => &n.text, + _ => "", + } +} + +/// Draws control `i` (`n`, with the prompt [`prompt_of`] gives) at its place. +fn control(ui: &mut Ui, drafts: &BTreeMap, place: &Place, (i, n, prompt): (usize, &UiNode, &str)) -> Shown { + let rect = egui::Rect::from_min_size(place.origin + egui::vec2(n.rect.x, n.rect.y), egui::vec2(n.rect.w, n.rect.h)); + let mut shown = Shown::default(); + let enabled = place.enabled; + let salt = (KIND, n.id); + // A control in a group or a panel is that container's child in the accessibility tree. + let builder = egui::UiBuilder::new().id_salt(n.id).max_rect(rect); + let builder = match place.parent { + Some(parent) => builder.accessibility_parent(parent), + None => builder, + }; + ui.scope_builder(builder, |ui| match n.kind { + UiKind::Dialog => {} + UiKind::Group => shown.container = Some(group(ui, rect, n, enabled)), + UiKind::Panel => shown.container = Some(panel(ui, rect, n, enabled)), + UiKind::StaticText => { + Text::new(n.text.clone()).show_at(ui, rect); + } + UiKind::Button => { + let mut button = Button::new(n.text.clone()).id_salt(salt).enabled(enabled); + if place.default { + button = button.variant(Variant::PRIMARY).default_stop(); + } + if clicked(&button.show_at(ui, rect)) { + shown.event = Some(UiEvent::Click(i)); + } + } + UiKind::CheckBox => { + // A check box is shown in the flow of its place, which draws its text after the box. + let out = Checkbox::new(Bind::given(n.checked)).label(n.text.clone()).id_salt(salt).enabled(enabled).show(ui); + if out.events.committed().is_some() { + shown.event = Some(UiEvent::Click(i)); + } + } + UiKind::RadioButton => { + let mut picked = false; + let out = RadioGroup::new(n.text.clone(), Bind::given(n.checked)).id_salt(salt).enabled(enabled).show_at(ui, rect, |ui, _| { + picked = clicked(&Radio::new(true).label(n.text.clone()).enabled(enabled).show(ui)); + }); + if picked || out.events.committed().is_some() { + shown.event = Some(UiEvent::Click(i)); + } + } + UiKind::EditText => shown = edit(ui, rect, drafts, enabled, (i, n, prompt)), + UiKind::DropDownList => { + let entries: Vec>> = n.items.iter().enumerate().map(|(k, item)| Entry::new(Some(k), item.clone())).collect(); + let out = Select::new(list_name(n, prompt), Bind::given(n.selection), &entries).id_salt(salt).enabled(enabled).show_at(ui, rect); + if let Some(k) = out.events.committed().copied().filter(|k| *k != n.selection) { + shown.event = Some(UiEvent::Change(i, UiValue::Index(k))); + } + } + UiKind::ListBox => { + let keys: Vec = (0..n.items.len()).collect(); + let source = keyed(&keys, |k: &usize| *k); + let selection = n.selection.map(Selection::single).unwrap_or_default(); + // Screen readers read the box as a list box, by its name or the static text before + // it, with the selected item as its value. The box has no opener to keep the keyboard + // focus, so a press on a row gives it the focus and the arrow keys go on from that row. + // The rows it shows are as many as fit in its height at the height the list draws them. + let row = RowHeight::Control.of(&StyleCx::of_env(ui.ctx(), &Env::of(ui))); + let out = List::::options(list_name(n, prompt)) + .focus_on_press(true) + .id_salt(salt) + .enabled(enabled) + .max_rows(list_rows(n.rect.h, row)) + .selection(Bind::given(selection)) + .show_items(ui, &source, &mut |k, _| ListRow::new(n.items.get(*k).cloned().unwrap_or_default())); + // A click activates a row; the arrow keys and typed letters select one. + for event in out.events { + let picked = match event { + CollectionEvent::Activate(k) => Some(k), + CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => keys.last().copied(), + _ => None, + }; + if let Some(k) = picked.filter(|k| n.selection != Some(*k)) { + shown.event = Some(UiEvent::Change(i, UiValue::Index(Some(k)))); + } + } + } + UiKind::Slider => { + let out = Slider::new(Bind::given(n.value), n.min..=n.max) + .label(screen_reader_name(n, prompt)) + .id_salt(salt) + .enabled(enabled) + .show_at(ui, rect); + if let Some(v) = out.events.committed().copied().filter(|v| *v != n.value) { + shown.event = Some(UiEvent::Change(i, UiValue::Number(v))); + } + } + UiKind::ProgressBar => { + Progress::new(n.fraction()).label(screen_reader_name(n, prompt)).id_salt(salt).show_at(ui, rect); + } + }); + shown +} + +/// A panel: a group box titled by its text over the panel's place; screen readers read it as a +/// group, disabled when the panel is. → the id of its node in the accessibility tree. +fn panel(ui: &mut Ui, rect: egui::Rect, n: &UiNode, enabled: bool) -> egui::Id { + let shown = GroupBox::new(n.text.clone(), None).id_salt((KIND, n.id)).enabled(enabled).show_at(ui, rect, |_, _| ()); + shown.output.response.id +} + +/// A group, which draws nothing; screen readers read it as a group called by the name the script +/// gave it, disabled when the group is. +/// → the id of its node in the accessibility tree. +fn group(ui: &mut Ui, rect: egui::Rect, n: &UiNode, enabled: bool) -> egui::Id { + let (enabled, name) = (enabled && ui.is_enabled(), n.name.clone()); + let r = ui.interact(rect, ui.scope_id().with("group"), egui::Sense::hover()); + r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Group, enabled, &name)); + r.id +} + +/// The name screen readers call a list box or a drop-down list `n` by: the visible static text +/// just before it, or else the name the script gave it, or else "Value". +fn list_name(n: &UiNode, prompt: &str) -> String { + match (prompt, n.name.as_str()) { + ("", "") => tl!("Value").to_string(), + ("", name) => name.to_string(), + (prompt, _) => prompt.to_string(), + } +} + +/// The name screen readers call a control with no visible label of its own (an edit field, a +/// slider or a progress bar) by: the visible static text just before it in its container, or else +/// the name the script gave it, or else a slider's or progress bar's text, or else "Text" for an +/// edit field and "Value" for the others. +pub(crate) fn screen_reader_name(n: &UiNode, prompt: &str) -> String { + let name = if !prompt.is_empty() { + prompt + } else if !n.name.is_empty() || n.kind == UiKind::EditText { + &n.name + } else { + &n.text + }; + match name { + "" if n.kind == UiKind::EditText => tl!("Text").to_string(), + "" => tl!("Value").to_string(), + name => name.to_string(), + } +} + +/// The most characters an edit field takes while it is typed: twice the longest text a script +/// accepts, so that a text that is too long can still be typed, refused and shortened. +pub(crate) const DRAFT_CHARS: usize = 2 * MAX_TEXT_BYTES; + +/// An edit field: its text is kept in the dialog while it is typed and given to the script when +/// the field loses the focus, or at Enter in a one-line field. +fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap, enabled: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown { + let mut text = drafts.get(&n.id).cloned().unwrap_or_else(|| n.text.clone()); + let mut field = TextField::new(screen_reader_name(n, prompt), Bind::bound(&mut text)) + .limit(DRAFT_CHARS) + .id_salt((KIND, n.id)) + .enabled(enabled) + .read_only(n.readonly); + if n.multiline { + field = field.lines(3); + } + let out = field.show_at(ui, rect); + let focused = out.response.has_focus(); + let mut draft = (out.events.value().is_some() || text != n.text).then(|| Some(text.clone())); + let committed = out.submitted || out.events.committed().is_some() || out.response.lost_focus(); + if committed && text != n.text && !n.readonly { + return Shown { event: Some(UiEvent::Change(i, UiValue::Text(text))), typing: true, container: None, draft: Some(None) }; + } + // A text the script refused stays in the field until the person changes it. + if !focused && text == n.text { + draft = Some(None); + } + Shown { event: None, typing: focused || committed, container: None, draft } +} + +/// The event in the dialog's fields, for the dialog `w`. +fn event_of(w: &ScriptUiDialog, d: &ScriptWindow) -> Result { + // A close names no control, so a `control` left from an earlier event does not stop it. + if d.event.as_deref() == Some("close") { + return Ok(UiEvent::Close); + } + let control = match &d.control { + Some(Value::Number(n)) => n.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("`control` must be a control's index, name or text")?, + Some(Value::String(s)) => w.find(s).ok_or_else(|| format!("the dialog has no control named {}", cut_to(s, 64)))?, + _ => 0, + }; + let list = w.nodes.get(control).is_some_and(|n| matches!(n.kind, UiKind::DropDownList | UiKind::ListBox)); + match (d.event.as_deref(), &d.value) { + (Some("click"), _) => Ok(UiEvent::Click(control)), + (Some("change"), Some(Value::String(t))) => Ok(UiEvent::Change(control, UiValue::Text(t.clone()))), + (Some("change"), Some(Value::Number(v))) if list => match list_index(v) { + Some(k) => Ok(UiEvent::Change(control, UiValue::Index(Some(k)))), + None => Err("a list's `value` must be an item index or null".into()), + }, + (Some("change"), Some(Value::Number(v))) => Ok(UiEvent::Change(control, UiValue::Number(v.as_f64().unwrap_or(f64::NAN)))), + (Some("change"), Some(Value::Null) | None) if list => Ok(UiEvent::Change(control, UiValue::Index(None))), + (Some("change"), _) => Err("a change's `value` must be a string, a number or null".into()), + _ => Err("`event` must be click, change or close".into()), + } +} + +/// Runs `f` on the open ScriptUI dialog; `None` when none is open. +pub(crate) fn with_window(app: &VectorcraftApp, f: impl FnOnce(&mut ScriptWindow) -> R) -> Option { + with_host(app, |host, _| host.get_mut::().map(f)).flatten() +} + +/// Whether the ScriptUI dialog is open and no other dialog is open over it. +pub(crate) fn is_top(app: &VectorcraftApp) -> bool { + with_host(app, |host, _| host.get::().is_some_and(|d| host.stack().is_top(d.id()))).unwrap_or(false) +} + +/// Whether the ScriptUI dialog is the top dialog and no popup or modal layer, its own drop-down +/// lists' included, is open over it. +pub(crate) fn uncovered(app: &VectorcraftApp) -> bool { + let Some(layer) = with_window(app, |d| d.layer) else { return false }; + let top = app.ui_ctx.as_ref().and_then(overlay::top); + is_top(app) && top.is_none_or(|top| Some(top) == layer) +} + +/// Opens, keeps or closes the ScriptUI dialog as the run's `show()` stands: it opens when a +/// `show()` waits, follows the dialog while the run waits at it (its heading follows a title a +/// handler changed), stays open while one of its handlers runs and closes when `show()` ends. A +/// dialog the script showed after closing the one that is open replaces it. +pub(crate) fn sync(app: &mut VectorcraftApp) { + let Some(showing) = app.session.script_window_showing() else { + super::script_run::forget::(app); + return; + }; + let open_for = with_window(app, |d| d.shown()); + if open_for.is_some_and(|shown| shown != showing.shown) { + super::script_run::forget::(app); + } + let waiting = app.session.script_window(); + if open_for == Some(showing.shown) { + with_window(app, |d| d.sync(waiting)); + } else if let Some(w) = waiting + && !super::script_run::busy(app) + { + with_host(app, |host, _| host.open(ScriptWindow::new(w))); + } +} + +/// Takes what the person did in the dialog, once per frame, and gives the run its next event while +/// it waits at the dialog. +pub(crate) fn pump(app: &mut VectorcraftApp) { + let Some((stop, cancel_asked, status)) = with_window(app, |d| (std::mem::take(&mut d.stop), std::mem::take(&mut d.cancel), d.status.take())) + else { + return; + }; + if let Some(e) = status { + app.status(e); + } + if stop { + app.session.script_request_stop(); + super::script_run::forget::(app); + return; + } + if cancel_asked && let Err(e) = cancel(app) { + app.status(e); + } + // Events wait in the queue while another dialog, such as the quit question, is open over it. + if !is_top(app) { + return; + } + let Some(w) = app.session.script_window() else { return }; + if with_window(app, |d| d.shown()) != Some(w.shown) { + return; + } + if let Some(event) = with_window(app, |d| d.next_event(&w)).flatten() { + // A typed text the script refuses (an earlier handler disabled its field, say) goes back + // in its field, so the person does not have to type it again. + let typed = match &event { + UiEvent::Change(i, UiValue::Text(t)) => w.nodes.get(*i).map(|n| (n.id, t.clone())), + _ => None, + }; + if let Err(e) = give(app, &w, event) { + if let Some((id, text)) = typed { + with_window(app, |d| d.drafts.insert(id, text)); + } + app.status(e); + } + } +} + +/// Gives the run `event` in the dialog `w` it waits at. Before a click or a close, the script is +/// given the text still typed in the dialog's fields first, and the click or close waits for its +/// next wait. +fn give(app: &mut VectorcraftApp, w: &ScriptUiDialog, event: UiEvent) -> Result<(), String> { + let mut events = vec![check_event(w, event)?]; + if matches!(events[0], UiEvent::Click(_) | UiEvent::Close) { + with_window(app, |d| d.commit_drafts(w, &mut events)).unwrap_or(Ok(()))?; + } + let mut events = events.into_iter(); + if let Some(first) = events.next() { + app.session.script_window_answer(first)?; + } + let later: Vec = events.filter_map(|e| queued(w, &e)).collect(); + with_window(app, |d| { + for q in later.into_iter().rev() { + d.queue.push_front(q); + } + }); + Ok(()) +} + +/// `ui.dialog.confirm`: gives the running script the event in the dialog's fields. The dialog stays +/// open for the script's next wait; an event it cannot take is an error. +pub(crate) fn confirm(app: &mut VectorcraftApp) -> Result { + let Some(w) = app.session.script_window() else { return Err("no script dialog waits".into()) }; + let event = with_window(app, |d| event_of(&w, d)).ok_or("no script dialog waits")??; + if with_window(app, |d| d.queue.is_empty()).unwrap_or(true) { + give(app, &w, event)?; + } else { + // Events the script has not had yet come first; this one, and the typed texts before a + // click or a close, go after them. + let mut events = vec![check_event(&w, event)?]; + if matches!(events[0], UiEvent::Click(_) | UiEvent::Close) { + with_window(app, |d| d.commit_drafts(&w, &mut events)).unwrap_or(Ok(()))?; + } + let later: Vec = events.iter().filter_map(|e| queued(&w, e)).collect(); + with_window(app, |d| d.queue.extend(later)); + } + with_window(app, |d| (d.event, d.control, d.value) = (None, None, None)); + Ok(Value::Null) +} + +/// Escape or `ui.dialog.cancel`: a click on the cancel button, or the close box when the dialog +/// has none or it cannot be clicked, after the text still typed in its fields. Events the script +/// has not had yet go after the ones before them. A typed text the script would refuse is an +/// error, and the dialog is left as it was. While a handler runs, the cancel waits for the dialog +/// the run waits at next. +pub(crate) fn cancel(app: &mut VectorcraftApp) -> Result<(), String> { + let Some(w) = app.session.script_window() else { + return with_window(app, |d| d.queue.push_back(Queued::Cancel)).ok_or_else(|| "no script dialog waits".to_string()); + }; + let mut events = vec![cancel_event(&w)]; + with_window(app, |d| d.commit_drafts(&w, &mut events)).unwrap_or(Ok(()))?; + let empty = with_window(app, |d| d.queue.is_empty()).unwrap_or(true); + // A cancel after other events goes last, and is a click on the cancel button of the dialog the + // run waits at when its turn comes, or its close box. + let deferred = !empty || events.len() > 1; + if deferred { + events.pop(); + } + let mut events = events.into_iter(); + if empty && let Some(first) = events.next() { + app.session.script_window_answer(first)?; + } + let mut later: Vec = events.filter_map(|e| queued(&w, &e)).collect(); + if deferred { + later.push(Queued::Cancel); + } + with_window(app, |d| d.queue.extend(later)); + Ok(()) +} + +/// `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` (`method`, with `params` naming the +/// dialog) when they name the ScriptUI dialog; `None` for any other dialog. `ui.dialog.set` sets +/// the fields as the host does, then answers with its `action`. +pub(crate) fn dialog_method(app: &mut VectorcraftApp, method: &str, params: &Value) -> Option> { + let ours = with_host(app, |host, _| craft::automation::dialogs::dialog_id(host, params).is_ok_and(|id| id == dialog_id(KIND)))?; + if !ours { + return None; + } + // The parameters each method takes, checked before anything is set or given. + let keys: &[&str] = if method == "ui.dialog.set" { &["dialog", "field", "value", "fields", "action"] } else { &["dialog"] }; + if let Err(e) = Params(params).only(None, keys) { + return Some(Err(e)); + } + let mut params = params.clone(); + let action = if method == "ui.dialog.set" { params.as_object_mut().and_then(|o| o.remove("action")) } else { None }; + let answer = match (method, action.as_ref().map(Value::as_str)) { + ("ui.dialog.confirm", _) | (_, Some(Some("confirm"))) => Some(true), + ("ui.dialog.cancel", _) | (_, Some(Some("cancel"))) => Some(false), + (_, None) => None, + (_, Some(_)) => return Some(Err("`action` must be confirm or cancel".into())), + }; + // A dialog open over it, such as the quit question, takes its answer first. + if answer == Some(true) && with_host(app, |host, _| host.stack().has_child(dialog_id(KIND))).unwrap_or(false) { + return Some(Err("the dialog refuses OK while a dialog open over it waits for its answer".into())); + } + // A set without an action sets a field, which the host's setter asks for when none is given. + if method == "ui.dialog.set" && (answer.is_none() || params.as_object().is_some_and(|o| o.keys().any(|k| k != "dialog"))) { + let set = with_host(app, |host, ctx| craft::automation::dialogs::dialog_method(host, ctx, method, ¶ms)).flatten(); + if let Some(Err(e)) = set { + return Some(Err(e)); + } + } + Some(match answer { + Some(true) => confirm(app), + Some(false) => cancel(app).map(|()| Value::Null), + // A set answers with the dialog it set, `{id, parent, key, fields}`, as the other dialogs' sets do. + None => Ok(with_host(app, |host, _| { + let id = dialog_id(KIND).value().to_string(); + craft::automation::dialogs::inspect(host).as_array().and_then(|open| open.iter().find(|d| d["id"] == id.as_str()).cloned()) + }) + .flatten() + .unwrap_or(Value::Null)), + }) +} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 3c16e1c64c..721ab04649 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6623,7 +6623,9 @@ liquify-list-end {0}, {1} {0} i {1} @msg is a confirm's answer, whose `value` must be true or false és la resposta d'un confirm, i el seu `value` ha de ser true o false @msg is longer than 16 KiB ocupa més de 16 KiB @msg is a prompt's answer, whose `value` must be a string or null és la resposta d'un prompt, i el seu `value` ha de ser una cadena o null -@msg must have `kind` alert, confirm or prompt ha de tenir `kind` alert, confirm o prompt +@msg must have `kind` alert, confirm, prompt or window ha de tenir `kind` alert, confirm, prompt o window +@msg is a window's answer, whose `value` must be a list of steps és la resposta d’una finestra, el `value` de la qual ha de ser una llista de passos +@msg has a step {i} that is not a valid click, change or close té un pas {i} que no és un clic, un canvi ni un tancament vàlid @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` només és per a una execució sense ningú a qui preguntar: a l'aplicació, la persona respon cada quadre de diàleg @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` ha de ser un nombre enter d’1 a {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` està imbricat en més de 64 nivells diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 5d3c18ca16..3ddc4cad9f 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9999,7 +9999,9 @@ breakText Glyphs Glyfy @msg more than {MAX_IMPORT} presets více než {MAX_IMPORT} přednastavení @msg moved must be [[x,y]…] moved musí být [[x,y]…] @msg must be an object with `kind` and `value` musí být objekt s `kind` a `value` -@msg must have `kind` alert, confirm or prompt musí mít `kind` alert, confirm nebo prompt +@msg must have `kind` alert, confirm, prompt or window musí mít `kind` alert, confirm, prompt nebo window +@msg is a window's answer, whose `value` must be a list of steps je odpověď okna, jejíž `value` musí být seznam kroků +@msg has a step {i} that is not a valid click, change or close má krok {i}, který není platné kliknutí, změna ani zavření @msg must have exactly `kind` and `value` musí mít právě `kind` a `value` @msg name (a toolbar's name) is required name (název panelu nástrojů) je povinné @msg name (a toolbar's name) must be a string name (název panelu nástrojů) musí být řetězec diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 20e0ebcd9b..71c6854402 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -235,7 +235,9 @@ liquify-list-end {0}, {1} {0} og {1} @msg is a confirm's answer, whose `value` must be true or false er svaret på en confirm, hvis `value` skal være true eller false @msg is longer than 16 KiB er længere end 16 KiB @msg is a prompt's answer, whose `value` must be a string or null er svaret på en prompt, hvis `value` skal være en streng eller null -@msg must have `kind` alert, confirm or prompt skal have `kind` alert, confirm eller prompt +@msg must have `kind` alert, confirm, prompt or window skal have `kind` alert, confirm, prompt eller window +@msg is a window's answer, whose `value` must be a list of steps er et vindues svar, hvis `value` skal være en liste over trin +@msg has a step {i} that is not a valid click, change or close har et trin {i}, der ikke er et gyldigt klik, en gyldig ændring eller en gyldig lukning @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` er kun til en kørsel uden nogen at spørge: i appen besvarer personen hver dialog @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` skal være et heltal fra 1 til {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` er indlejret mere end 64 niveauer dybt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index dee986b362..028d816bb0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8755,7 +8755,9 @@ breakText Glyphs Glyphen @msg missing `picks` `picks` fehlt @msg missing `word` `word` fehlt @msg must be an object with `kind` and `value` muss ein Objekt mit `kind` und `value` sein -@msg must have `kind` alert, confirm or prompt muss `kind` alert, confirm oder prompt haben +@msg must have `kind` alert, confirm, prompt or window muss `kind` alert, confirm, prompt oder window haben +@msg is a window's answer, whose `value` must be a list of steps ist die Antwort auf ein Fenster, deren `value` eine Liste von Schritten sein muss +@msg has a step {i} that is not a valid click, change or close hat einen Schritt {i}, der kein gültiger Klick, keine gültige Änderung und kein gültiges Schließen ist @msg must have exactly `kind` and `value` muss genau `kind` und `value` haben @msg needs a closing quote after the name braucht ein schließendes Anführungszeichen nach dem Namen @msg needs a name braucht einen Namen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7a1f77363a..7f7ff3259a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2815,7 +2815,9 @@ liquify-list-end {0}, {1} {0} και {1} @msg is a confirm's answer, whose `value` must be true or false είναι απάντηση σε confirm, οπότε το `value` πρέπει να είναι true ή false @msg is longer than 16 KiB είναι μεγαλύτερο από 16 KiB @msg is a prompt's answer, whose `value` must be a string or null είναι απάντηση σε prompt, οπότε το `value` πρέπει να είναι συμβολοσειρά ή null -@msg must have `kind` alert, confirm or prompt πρέπει να έχει `kind` alert, confirm ή prompt +@msg must have `kind` alert, confirm, prompt or window πρέπει να έχει `kind` alert, confirm, prompt ή window +@msg is a window's answer, whose `value` must be a list of steps είναι απάντηση παραθύρου, της οποίας το `value` πρέπει να είναι λίστα βημάτων +@msg has a step {i} that is not a valid click, change or close έχει ένα βήμα {i} που δεν είναι έγκυρο κλικ, αλλαγή ή κλείσιμο @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog το `answers` είναι μόνο για εκτέλεση χωρίς κανέναν να ερωτηθεί: στην εφαρμογή, το άτομο απαντά σε κάθε παράθυρο διαλόγου @msg `maxFuel` must be a whole number from 1 to {_1} το `maxFuel` πρέπει να είναι ακέραιος από 1 έως {_1} @msg `args{place}` is nested more than 64 levels deep το `args{place}` έχει ένθεση μεγαλύτερη των 64 επιπέδων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a470c3a68e..55cc33bc39 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5093,7 +5093,9 @@ liquify-list-end {0}, {1} {0}, {1} @msg is a confirm's answer, whose `value` must be true or false es la respuesta de un confirm, cuyo `value` debe ser true o false @msg is longer than 16 KiB ocupa más de 16 KiB @msg is a prompt's answer, whose `value` must be a string or null es la respuesta de un prompt, cuyo `value` debe ser una cadena o null -@msg must have `kind` alert, confirm or prompt debe tener `kind` alert, confirm o prompt +@msg must have `kind` alert, confirm, prompt or window debe tener `kind` alert, confirm, prompt o window +@msg is a window's answer, whose `value` must be a list of steps es la respuesta de una ventana, cuyo `value` debe ser una lista de pasos +@msg has a step {i} that is not a valid click, change or close tiene un paso {i} que no es un clic, un cambio ni un cierre válido @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` solo es para una ejecución sin nadie a quien preguntar: en la aplicación, la persona responde cada cuadro de diálogo @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` debe ser un número entero de 1 a {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` está anidado a más de 64 niveles diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 359a9e4521..a38dae760e 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5336,7 +5336,9 @@ liquify-list-end {0}, {1} {0} ja {1} @msg is a confirm's answer, whose `value` must be true or false on confirm-vastaus, joten sen `value`-arvon on oltava true tai false @msg is longer than 16 KiB on pidempi kuin 16 KiB @msg is a prompt's answer, whose `value` must be a string or null on prompt-vastaus, joten sen `value`-arvon on oltava merkkijono tai null -@msg must have `kind` alert, confirm or prompt `kind`-arvon on oltava alert, confirm tai prompt +@msg must have `kind` alert, confirm, prompt or window `kind`-arvon on oltava alert, confirm, prompt tai window +@msg is a window's answer, whose `value` must be a list of steps on ikkunan vastaus, jonka `value`-arvon on oltava luettelo vaiheista +@msg has a step {i} that is not a valid click, change or close sisältää vaiheen {i}, joka ei ole kelvollinen napsautus, muutos tai sulkeminen @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` on vain ajolle, jossa ei ole ketään kysyttävää: sovelluksessa henkilö vastaa jokaiseen valintaikkunaan @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` on oltava kokonaisluku väliltä 1–{_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` on sisäkkäin yli 64 tason syvyydellä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index de762ee5b3..6758e7b5cd 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9859,7 +9859,9 @@ breakText Glyphs Glyphes @msg more than {MAX_IMPORT} presets plus de {MAX_IMPORT} paramètres prédéfinis @msg moved must be [[x,y]…] moved doit être [[x,y]…] @msg must be an object with `kind` and `value` doit être un objet avec `kind` et `value` -@msg must have `kind` alert, confirm or prompt doit avoir `kind` alert, confirm ou prompt +@msg must have `kind` alert, confirm, prompt or window doit avoir `kind` alert, confirm, prompt ou window +@msg is a window's answer, whose `value` must be a list of steps est la réponse d’une fenêtre, dont la `value` doit être une liste d’étapes +@msg has a step {i} that is not a valid click, change or close a une étape {i} qui n’est ni un clic, ni une modification, ni une fermeture valide @msg must have exactly `kind` and `value` doit avoir exactement `kind` et `value` @msg name (a toolbar's name) is required name (le nom d’une barre d’outils) est obligatoire @msg name (a toolbar's name) must be a string name (le nom d’une barre d’outils) doit être une chaîne diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 147e1ad3ad..5e149c2d9b 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7826,7 +7826,9 @@ liquify-list-end {0}, {1} {0} और {1} @msg is a confirm's answer, whose `value` must be true or false यह confirm का उत्तर है, इसलिए इसका `value` true या false होना चाहिए @msg is longer than 16 KiB 16 KiB से लंबा है @msg is a prompt's answer, whose `value` must be a string or null यह prompt का उत्तर है, इसलिए इसका `value` स्ट्रिंग या null होना चाहिए -@msg must have `kind` alert, confirm or prompt `kind` alert, confirm या prompt होना चाहिए +@msg must have `kind` alert, confirm, prompt or window `kind` alert, confirm, prompt या window होना चाहिए +@msg is a window's answer, whose `value` must be a list of steps एक window का उत्तर है, जिसका `value` चरणों की सूची होना चाहिए +@msg has a step {i} that is not a valid click, change or close में चरण {i} मान्य क्लिक, बदलाव या बंद करना नहीं है @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` केवल ऐसे रन के लिए है जिसमें पूछने के लिए कोई नहीं है: ऐप में, व्यक्ति हर डायलॉग का उत्तर देता है @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 1 से {_1} तक की पूर्ण संख्या होनी चाहिए @msg `args{place}` is nested more than 64 levels deep `args{place}` 64 से अधिक स्तर गहराई तक नेस्ट किया गया है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c353c82913..3a36e89b7d 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9869,7 +9869,9 @@ breakText Glyphs Glifák @msg more than {MAX_IMPORT} presets több mint {MAX_IMPORT} előbeállítás @msg moved must be [[x,y]…] moved: [[x,y]…] kell @msg must be an object with `kind` and `value` `kind` és `value` kulcsot tartalmazó objektum kell -@msg must have `kind` alert, confirm or prompt a `kind` értéke alert, confirm vagy prompt kell legyen +@msg must have `kind` alert, confirm, prompt or window a `kind` értéke alert, confirm, prompt vagy window kell legyen +@msg is a window's answer, whose `value` must be a list of steps egy ablak válasza, amelynek `value` értéke lépések listája kell legyen +@msg has a step {i} that is not a valid click, change or close {i}. lépése nem érvényes kattintás, módosítás vagy bezárás @msg must have exactly `kind` and `value` pontosan a `kind` és a `value` kulcsot kell tartalmaznia @msg name (a toolbar's name) is required name (egy eszköztár neve): kötelező @msg name (a toolbar's name) must be a string name (egy eszköztár neve): karakterlánc kell diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index bf40c9a838..931d8095a0 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -141,7 +141,9 @@ @msg is a confirm's answer, whose `value` must be true or false adalah jawaban confirm, yang `value`-nya harus true atau false @msg is longer than 16 KiB lebih panjang dari 16 KiB @msg is a prompt's answer, whose `value` must be a string or null adalah jawaban prompt, yang `value`-nya harus berupa string atau null -@msg must have `kind` alert, confirm or prompt harus memiliki `kind` alert, confirm, atau prompt +@msg must have `kind` alert, confirm, prompt or window harus memiliki `kind` alert, confirm, prompt, atau window +@msg is a window's answer, whose `value` must be a list of steps adalah jawaban jendela, yang `value`-nya harus berupa daftar langkah +@msg has a step {i} that is not a valid click, change or close memiliki langkah {i} yang bukan klik, perubahan, atau penutupan yang valid @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` hanya untuk proses tanpa orang yang dapat ditanya: di aplikasi, pengguna menjawab setiap dialog @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` harus berupa bilangan bulat dari 1 sampai {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` bersarang lebih dari 64 tingkat diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 29f2291dc0..d79e23f6ca 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8804,7 +8804,9 @@ breakText Glyphs Glifi @msg missing `picks` `picks` mancante @msg missing `word` `word` mancante @msg must be an object with `kind` and `value` deve essere un oggetto con `kind` e `value` -@msg must have `kind` alert, confirm or prompt deve avere `kind` alert, confirm o prompt +@msg must have `kind` alert, confirm, prompt or window deve avere `kind` alert, confirm, prompt o window +@msg is a window's answer, whose `value` must be a list of steps è la risposta di una finestra, il cui `value` deve essere un elenco di passaggi +@msg has a step {i} that is not a valid click, change or close ha un passaggio {i} che non è un clic, una modifica o una chiusura validi @msg must have exactly `kind` and `value` deve avere esattamente `kind` e `value` @msg needs a closing quote after the name richiede una virgoletta di chiusura dopo il nome @msg needs a name richiede un nome diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 8cd285d99d..2aaf78daca 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7618,7 +7618,9 @@ axis Y Axis Y 軸 @msg missing `picks` `picks` がありません @msg missing `word` `word` がありません @msg must be an object with `kind` and `value` には `kind` と `value` を持つオブジェクトを指定してください -@msg must have `kind` alert, confirm or prompt の `kind` には alert、confirm、prompt のいずれかを指定してください +@msg must have `kind` alert, confirm, prompt or window の `kind` には alert、confirm、prompt、window のいずれかを指定してください +@msg is a window's answer, whose `value` must be a list of steps は window の回答で、`value` には手順のリストを指定してください +@msg has a step {i} that is not a valid click, change or close の手順 {i} は有効なクリック、変更、閉じる操作のいずれでもありません @msg must have exactly `kind` and `value` には `kind` と `value` だけを指定してください @msg needs a closing quote after the name 名前の後に閉じ引用符が必要です @msg needs a name 名前が必要です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index edfe2109d7..17619de380 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1088,7 +1088,9 @@ @msg more than {MAX_IMPORT} presets {MAX_IMPORT}-ზე მეტი პრესეტი @msg moved must be [[x,y]…] moved უნდა იყოს [[x,y]…] @msg must be an object with `kind` and `value` უნდა იყოს ობიექტი `kind`-ით და `value`-თი -@msg must have `kind` alert, confirm or prompt `kind` უნდა იყოს alert, confirm ან prompt +@msg must have `kind` alert, confirm, prompt or window `kind` უნდა იყოს alert, confirm, prompt ან window +@msg is a window's answer, whose `value` must be a list of steps არის ფანჯრის პასუხი, რომლის `value` უნდა იყოს ნაბიჯების სია +@msg has a step {i} that is not a valid click, change or close შეიცავს ნაბიჯს {i}, რომელიც არ არის სწორი დაწკაპუნება, ცვლილება ან დახურვა @msg must have exactly `kind` and `value` უნდა ჰქონდეს ზუსტად `kind` და `value` @msg name (a toolbar's name) is required საჭიროა name (ხელსაწყოთა ზოლის სახელი) @msg name (a toolbar's name) must be a string name (ხელსაწყოთა ზოლის სახელი) უნდა იყოს სტრიქონი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fa5c376f34..5fc49c5942 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -9637,7 +9637,9 @@ breakText Glyphs 글리프 @msg more than {MAX_IMPORT} presets 사전 설정이 {MAX_IMPORT}개보다 많습니다 @msg moved must be [[x,y]…] moved는 [[x,y]…]여야 합니다 @msg must be an object with `kind` and `value` `kind`와 `value`가 있는 개체여야 합니다 -@msg must have `kind` alert, confirm or prompt `kind`가 alert, confirm 또는 prompt여야 합니다 +@msg must have `kind` alert, confirm, prompt or window `kind`가 alert, confirm, prompt 또는 window여야 합니다 +@msg is a window's answer, whose `value` must be a list of steps 창의 답이며, `value`는 단계 목록이어야 합니다 +@msg has a step {i} that is not a valid click, change or close 단계 {i}이(가) 올바른 클릭, 변경 또는 닫기가 아닙니다 @msg must have exactly `kind` and `value` `kind`와 `value`만 있어야 합니다 @msg name (a toolbar's name) is required name(도구 막대 이름)이 필요합니다 @msg name (a toolbar's name) must be a string name(도구 막대 이름)은 문자열이어야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index bea75205b0..944709394c 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -7503,7 +7503,9 @@ imageTrace Outline Contour @msg more than {MAX_IMPORT} presets meer dan {MAX_IMPORT} voorinstellingen @msg moved must be [[x,y]…] moved moet [[x,y]…] zijn @msg must be an object with `kind` and `value` moet een object met `kind` en `value` zijn -@msg must have `kind` alert, confirm or prompt moet `kind` alert, confirm of prompt hebben +@msg must have `kind` alert, confirm, prompt or window moet `kind` alert, confirm, prompt of window hebben +@msg is a window's answer, whose `value` must be a list of steps is het antwoord van een venster, waarvan `value` een lijst met stappen moet zijn +@msg has a step {i} that is not a valid click, change or close heeft een stap {i} die geen geldige klik, wijziging of sluiting is @msg must have exactly `kind` and `value` moet precies `kind` en `value` hebben @msg name (a toolbar's name) is required name (de naam van een werkbalk) is vereist @msg name (a toolbar's name) must be a string name (de naam van een werkbalk) moet een string zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0dc2afe500..c2176d417b 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -9008,7 +9008,9 @@ breakText Glyphs Glify @msg missing `picks` brak `picks` @msg missing `word` brak `word` @msg must be an object with `kind` and `value` musi być obiektem z `kind` i `value` -@msg must have `kind` alert, confirm or prompt `kind` musi mieć wartość alert, confirm lub prompt +@msg must have `kind` alert, confirm, prompt or window `kind` musi mieć wartość alert, confirm, prompt lub window +@msg is a window's answer, whose `value` must be a list of steps jest odpowiedzią okna, której `value` musi być listą kroków +@msg has a step {i} that is not a valid click, change or close ma krok {i}, który nie jest prawidłowym kliknięciem, zmianą ani zamknięciem @msg must have exactly `kind` and `value` musi mieć dokładnie `kind` i `value` @msg needs a closing quote after the name wymaga zamykającego cudzysłowu po nazwie @msg needs a name wymaga nazwy diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 43e8ca76f8..2d09663de8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -10061,7 +10061,9 @@ swatch Yellow Green Verde-amarelado @msg more than {MAX_IMPORT} presets mais de {MAX_IMPORT} predefinições @msg moved must be [[x,y]…] moved deve ser [[x,y]…] @msg must be an object with `kind` and `value` deve ser um objeto com `kind` e `value` -@msg must have `kind` alert, confirm or prompt deve ter `kind` alert, confirm ou prompt +@msg must have `kind` alert, confirm, prompt or window deve ter `kind` alert, confirm, prompt ou window +@msg is a window's answer, whose `value` must be a list of steps é a resposta de uma janela, cujo `value` deve ser uma lista de etapas +@msg has a step {i} that is not a valid click, change or close tem uma etapa {i} que não é um clique, uma alteração nem um fechamento válido @msg must have exactly `kind` and `value` deve ter exatamente `kind` e `value` @msg name (a toolbar's name) is required name (o nome de uma barra de ferramentas) é obrigatório @msg name (a toolbar's name) must be a string name (o nome de uma barra de ferramentas) deve ser uma string diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 84edfc7d71..8742efa528 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5118,7 +5118,9 @@ liquify-list-end {0}, {1} {0} и {1} @msg is a confirm's answer, whose `value` must be true or false является ответом на confirm, поэтому его `value` должно быть true или false @msg is longer than 16 KiB длиннее 16 КиБ @msg is a prompt's answer, whose `value` must be a string or null является ответом на prompt, поэтому его `value` должно быть строкой или null -@msg must have `kind` alert, confirm or prompt должен иметь `kind` alert, confirm или prompt +@msg must have `kind` alert, confirm, prompt or window должен иметь `kind` alert, confirm, prompt или window +@msg is a window's answer, whose `value` must be a list of steps является ответом окна, `value` которого должен быть списком шагов +@msg has a step {i} that is not a valid click, change or close содержит шаг {i}, который не является допустимым щелчком, изменением или закрытием @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` предназначен только для запуска, в котором некого спросить: в приложении человек сам отвечает на каждое диалоговое окно @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` должен быть целым числом от 1 до {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` вложен глубже 64 уровней diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e9611dcd53..4cbce94eb7 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4991,7 +4991,9 @@ liquify-list-end {0}, {1} {0} och {1} @msg is a confirm's answer, whose `value` must be true or false är svaret på en confirm, vars `value` måste vara true eller false @msg is longer than 16 KiB är längre än 16 KiB @msg is a prompt's answer, whose `value` must be a string or null är svaret på en prompt, vars `value` måste vara en sträng eller null -@msg must have `kind` alert, confirm or prompt måste ha `kind` alert, confirm eller prompt +@msg must have `kind` alert, confirm, prompt or window måste ha `kind` alert, confirm, prompt eller window +@msg is a window's answer, whose `value` must be a list of steps är ett fönsters svar, vars `value` måste vara en lista med steg +@msg has a step {i} that is not a valid click, change or close har ett steg {i} som inte är ett giltigt klick, en giltig ändring eller en giltig stängning @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` är bara för en körning utan någon att fråga: i appen svarar personen på varje dialogruta @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` måste vara ett heltal från 1 till {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` är kapslat mer än 64 nivåer djupt diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 0ede2da0a9..39fff8766f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7996,7 +7996,9 @@ axis Y Axis Y ekseni @msg missing `picks` `picks` eksik @msg missing `word` `word` eksik @msg must be an object with `kind` and `value` `kind` ve `value` içeren bir nesne olmalıdır -@msg must have `kind` alert, confirm or prompt `kind` değeri alert, confirm veya prompt olmalıdır +@msg must have `kind` alert, confirm, prompt or window `kind` değeri alert, confirm, prompt veya window olmalıdır +@msg is a window's answer, whose `value` must be a list of steps bir pencerenin yanıtıdır ve `value` değeri bir adım listesi olmalıdır +@msg has a step {i} that is not a valid click, change or close içindeki {i}. adım geçerli bir tıklama, değişiklik veya kapatma değil @msg must have exactly `kind` and `value` yalnızca `kind` ve `value` içermelidir @msg needs a closing quote after the name addan sonra bir kapanış tırnağı gerekir @msg needs a name bir ad gerekir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 25978ab078..9dd4c3e25e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9638,7 +9638,9 @@ breakText Glyphs Гліфи @msg more than {MAX_IMPORT} presets понад {MAX_IMPORT} наборів @msg moved must be [[x,y]…] moved має бути [[x,y]…] @msg must be an object with `kind` and `value` має бути об’єктом із `kind` і `value` -@msg must have `kind` alert, confirm or prompt повинен мати `kind` зі значенням alert, confirm або prompt +@msg must have `kind` alert, confirm, prompt or window повинен мати `kind` зі значенням alert, confirm, prompt або window +@msg is a window's answer, whose `value` must be a list of steps є відповіддю вікна, `value` якої має бути списком кроків +@msg has a step {i} that is not a valid click, change or close має крок {i}, який не є допустимим клацанням, зміною або закриттям @msg must have exactly `kind` and `value` повинен мати рівно `kind` і `value` @msg name (a toolbar's name) is required name (ім’я панелі інструментів) є обов’язковим @msg name (a toolbar's name) must be a string name (ім’я панелі інструментів) має бути рядком diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index d82a764cd4..828d2e214f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5617,7 +5617,9 @@ liquify-list-end {0}, {1} {0} và {1} @msg is a confirm's answer, whose `value` must be true or false là câu trả lời cho confirm, nên `value` phải là true hoặc false @msg is longer than 16 KiB dài hơn 16 KiB @msg is a prompt's answer, whose `value` must be a string or null là câu trả lời cho prompt, nên `value` phải là chuỗi hoặc null -@msg must have `kind` alert, confirm or prompt phải có `kind` là alert, confirm hoặc prompt +@msg must have `kind` alert, confirm, prompt or window phải có `kind` là alert, confirm, prompt hoặc window +@msg is a window's answer, whose `value` must be a list of steps là câu trả lời của một cửa sổ, có `value` phải là danh sách các bước +@msg has a step {i} that is not a valid click, change or close có bước {i} không phải là một lần nhấp, thay đổi hoặc đóng hợp lệ @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` chỉ dành cho lần chạy không có ai để hỏi: trong ứng dụng, người dùng trả lời từng hộp thoại @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` phải là số nguyên từ 1 đến {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` lồng sâu hơn 64 cấp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 3d3e70b205..9c4a1c4a77 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -9016,7 +9016,9 @@ breakText Glyphs 字形 @msg missing `picks` 缺少 `picks` @msg missing `word` 缺少 `word` @msg must be an object with `kind` and `value` 必须是包含 `kind` 和 `value` 的对象 -@msg must have `kind` alert, confirm or prompt `kind` 必须是 alert、confirm 或 prompt +@msg must have `kind` alert, confirm, prompt or window `kind` 必须是 alert、confirm、prompt 或 window +@msg is a window's answer, whose `value` must be a list of steps 是窗口的回答,其 `value` 必须是步骤列表 +@msg has a step {i} that is not a valid click, change or close 的第 {i} 步不是有效的点击、更改或关闭 @msg must have exactly `kind` and `value` 必须只包含 `kind` 和 `value` @msg needs a closing quote after the name 名称后需要右引号 @msg needs a name 需要名称 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 735995ad33..f04f19c97f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8950,7 +8950,9 @@ breakText Glyphs 字符 @msg missing `picks` 未提供 `picks` @msg missing `word` 未提供 `word` @msg must be an object with `kind` and `value` 必須是包含 `kind` 和 `value` 的物件 -@msg must have `kind` alert, confirm or prompt `kind` 必須是 alert、confirm 或 prompt +@msg must have `kind` alert, confirm, prompt or window `kind` 必須是 alert、confirm、prompt 或 window +@msg is a window's answer, whose `value` must be a list of steps 是視窗的回答,其 `value` 必須是步驟清單 +@msg has a step {i} that is not a valid click, change or close 的第 {i} 步不是有效的點按、變更或關閉 @msg must have exactly `kind` and `value` 只能有 `kind` 和 `value` @msg needs a closing quote after the name 名稱之後需要結尾引號 @msg needs a name 需要名稱 diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 32d5adf9a8..ee469adf18 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -1,13 +1,15 @@ //! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with -//! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer. +//! `alert`, `confirm`, `prompt`, a ScriptUI dialog's `show()` or a `File` or `Folder` file dialog, +//! waits for the person's answer. use serde_json::{Value, json}; use vectorcraft_engine::WindowView; use crate::VectorcraftApp; use crate::dialogs::script_run::{self, GrowthQuestion, ScriptFiles, ScriptNotice}; +use crate::dialogs::script_window; /// Advances the running script by one slice, or asks what its growth needs asked. pub fn poll(app: &mut VectorcraftApp) { @@ -38,6 +40,7 @@ pub fn poll(app: &mut VectorcraftApp) { }; script_run::forget::(app); script_run::settle_close(app); + script_window::sync(app); match result { // The commands it ran are journaled now: a recording they no longer fit in names its limit. Ok(_) => { @@ -148,32 +151,36 @@ fn show_notes(app: &mut VectorcraftApp, notes: Vec) { } } -/// Opens what the run waits at, once no other dialog is open: the script's own dialog, or the -/// question about its growth. Closes the script's dialog when the run no longer waits at it. -/// → true while the run waits. +/// Opens what the run waits at, once no other dialog is open, or over the script's ScriptUI dialog: +/// the script's own dialog, or the question about its growth. Closes the script's dialog when the +/// run no longer waits at it, and the ScriptUI dialog when its `show()` ends. → true while the run +/// waits. fn ask(app: &mut VectorcraftApp) -> bool { + script_window::sync(app); if let Some(picker) = app.session.script_picker() { - if !script_run::busy(app) { + if script_run::can_ask(app) { script_run::open_picker(app, picker); } return true; } script_run::forget::(app); if let Some(dialog) = app.session.script_dialog() { - if !script_run::busy(app) { + if script_run::can_ask(app) { script_run::open_notice(app, &dialog); } return true; } // A run asked to stop no longer waits at its dialog. script_run::forget::(app); + // A run past its growth allowance asks about it first, also when its ScriptUI dialog waits + // again. if app.session.script_waiting() { - if !script_run::busy(app) { + if script_run::can_ask(app) { script_run::open_growth(app); } return true; } - false + app.session.script_window().is_some() } /// Runs the script of `params` (`script.run`'s) that the person chose from File › Scripts, after diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index bdd82189bd..b2bfcc6880 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -44,6 +44,7 @@ mod screenmode; mod script_check; mod script_dialogs; mod script_run; +mod script_window; mod scripts_menu; mod scrub; mod selectall; diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs new file mode 100644 index 0000000000..b605447733 --- /dev/null +++ b/crates/ui-egui/src/tests/script_window.rs @@ -0,0 +1,1133 @@ +//! A script's ScriptUI dialog in the app: it opens when `show()` waits, takes clicks and changes +//! from the person and from `ui.dialog.confirm`, Enter and Escape, Stop, and quitting while it +//! waits. + +use craft::automation::{ControlRequest, Reply}; +use craft::ui::dialog::StackDialog as _; +use serde_json::{Value, json}; +use vectorcraft_engine::script::{UiEvent, UiKind, UiValue}; + +use super::script_dialogs::{app, frame, is_open, key, open_id, pump}; +use crate::dialogs::script_run::{CLOSE_KIND, CloseQuestion, GROWTH_KIND, GrowthQuestion, ScriptNotice, with_host}; +use crate::dialogs::script_window::{self, KIND, Queued, ScriptWindow, with_window}; +use crate::{VectorcraftApp, menus, script_runs}; + +fn objects(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +const DRAW: &str = "vc.run('shape.rectangle', {x:0,y:0,width:10,height:10});"; + +const FORM: &str = "var w = new Window('dialog', 'Make'); var name = w.add('edittext', undefined, 'first', {name: 'name'}); \ + var bold = w.add('checkbox', undefined, 'Bold'); bold.onClick = function () { name.text = 'clicked'; }; \ + w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel');"; + +fn start(app: &mut VectorcraftApp, source: &str) { + menus::run_ui_command(app, "ui.runScript", &json!({"source": source, "name": "w.js"})).unwrap().unwrap(); +} + +/// Polls the run until it ends, or until its ScriptUI dialog is open and it waits (true). +fn until_window(app: &mut VectorcraftApp) -> bool { + for _ in 0..10_000 { + if !app.session.script_running() { + return false; + } + script_runs::poll(app); + if is_open::(app) && app.session.script_window().is_some() { + return true; + } + } + panic!("the script neither ended nor opened its dialog"); +} + +/// Sets the dialog's fields as `ui.dialog.set` does, then gives the event as `ui.dialog.confirm` +/// does. +fn give(app: &mut VectorcraftApp, event: Value) -> Result { + let id = open_id(app, KIND); + for field in ["event", "control", "value"] { + let value = event.get(field).cloned().unwrap_or(Value::Null); + with_host(app, |host, ctx| host.set_json_field(ctx, id, field, value)).unwrap()?; + } + script_window::confirm(app) +} + +/// One pass of the dialog host, then the frame's pump, which gives the run the next event that +/// waits. +fn step(app: &mut VectorcraftApp, events: Vec) { + frame(app, events); + pump(app); +} + +/// Closes the question quitting asks with Cancel, as Escape does, without the frame's pump. +fn cancel_close_question(app: &mut VectorcraftApp) { + let id = open_id(app, CLOSE_KIND); + with_host(app, |host, ctx| host.cancel_by_id(ctx, id)).unwrap(); + with_host(app, |host, _| host.take::()); +} + +fn typed(app: &VectorcraftApp, i: usize) -> Option { + with_window(app, |d| d.typed(i).map(str::to_string)).flatten() +} + +fn type_text(app: &VectorcraftApp, i: usize, text: &str) { + with_window(app, |d| d.type_text(i, text)).unwrap(); +} + +fn queued(app: &VectorcraftApp) -> Vec { + with_window(app, |d| d.queued().iter().cloned().collect()).unwrap_or_default() +} + +fn title(app: &VectorcraftApp) -> String { + with_window(app, |d| d.json_fields().unwrap()["title"].as_str().unwrap_or_default().to_string()).unwrap() +} + +fn log(app: &VectorcraftApp) -> Value { + app.session.script_report().unwrap()["log"].clone() +} + +#[test] +fn the_dialog_takes_events_and_stays_open_while_its_handlers_run() { + let mut app = app(); + start(&mut app, &format!("{DRAW} {FORM} var r = w.show(); vc.log([r, name.text, bold.value]);")); + assert!(until_window(&mut app)); + assert_eq!(title(&app), "Make"); + step(&mut app, Vec::new()); + give(&mut app, json!({"event": "click", "control": "Bold"})).unwrap(); + assert!(is_open::(&app), "the dialog stays open for the next wait"); + assert!(until_window(&mut app)); + assert_eq!(app.session.script_window().unwrap().nodes[1].text, "clicked", "the handler changed the field"); + assert!(give(&mut app, json!({"event": "click", "control": 99})).is_err()); + assert!(give(&mut app, json!({"event": "wave"})).is_err()); + give(&mut app, json!({"event": "change", "control": "name", "value": "Ann"})).unwrap(); + assert!(until_window(&mut app)); + step(&mut app, vec![key(egui::Key::Enter)]); + assert!(!until_window(&mut app), "Enter clicks OK, which closes the dialog"); + assert_eq!(log(&app), json!([[1, "Ann", true]])); + assert!(!is_open::(&app)); + assert_eq!(objects(&app), 1); +} + +#[test] +fn text_still_in_a_field_reaches_the_script_before_a_click() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log([w.show(), name.text]);")); + assert!(until_window(&mut app)); + let w = app.session.script_window().unwrap(); + with_window(&app, |d| { + d.type_text(1, "Ann"); + let mut events = vec![UiEvent::Click(3)]; + d.commit_drafts(&w, &mut events).unwrap(); + assert_eq!(events, vec![UiEvent::Change(1, UiValue::Text("Ann".into())), UiEvent::Click(3)]); + assert!(d.typed(1).is_none(), "the text is given once"); + for e in &events { + d.queue(e); + } + }) + .unwrap(); + step(&mut app, Vec::new()); + assert!(until_window(&mut app), "the script takes the change and waits again"); + step(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([[1, "Ann"]])); +} + +#[test] +fn escape_clicks_the_cancel_button_and_closes_a_dialog_without_one() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + step(&mut app, vec![key(egui::Key::Escape)]); + assert!(!until_window(&mut app)); + // The next frame takes down the dialog's window. + step(&mut app, Vec::new()); + assert!(!crate::dialogs::script_run::busy(&app), "the dialog Escape closed leaves nothing open"); + assert_eq!(log(&app), json!([2])); + start(&mut app, "var w = new Window('dialog'); w.add('statictext', undefined, 'Hi'); vc.log(w.show());"); + assert!(until_window(&mut app)); + script_window::cancel(&mut app).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([0])); +} + +#[test] +fn escape_keeps_the_dialog_open_until_the_script_closes_it() { + let mut app = app(); + start(&mut app, "var w = new Window('dialog'); w.add('edittext', undefined, 'a'); w.onClose = function () { return false; }; vc.log(w.show());"); + assert!(until_window(&mut app)); + type_text(&app, 1, "typed"); + script_window::cancel(&mut app).unwrap(); + assert!(is_open::(&app), "the dialog stays open"); + assert_eq!(queued(&app), vec![Queued::Cancel], "with the cancel, which has no button to click and closes, after the typed text"); + assert!(until_window(&mut app), "the script takes the text and waits again"); + assert_eq!(app.session.script_window().unwrap().nodes[1].text, "typed"); + step(&mut app, Vec::new()); + assert!(until_window(&mut app), "onClose kept the dialog open"); + assert!(queued(&app).is_empty()); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +#[test] +fn escape_gives_the_typed_text_before_the_cancel_click() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var e = w.add('edittext', undefined, 'old'); var c = w.add('button', undefined, 'Cancel'); \ + c.onClick = function () { vc.log(e.text); w.close(2); }; vc.log(w.show());", + ); + assert!(until_window(&mut app)); + type_text(&app, 1, "typed"); + script_window::cancel(&mut app).unwrap(); + assert!(until_window(&mut app), "the script takes the text and waits again"); + step(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on Cancel closes the dialog"); + assert_eq!(log(&app), json!(["typed", 2])); +} + +#[test] +fn a_second_dialog_replaces_the_first() { + let mut app = app(); + start( + &mut app, + "var a = new Window('dialog', 'A'); a.add('edittext', undefined, 'x'); a.add('button', undefined, 'OK'); a.show(); \ + var b = new Window('dialog', 'B'); b.add('edittext', undefined, 'y'); b.add('button', undefined, 'OK'); vc.log([b.show(), b.children[0].text]);", + ); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + type_text(&app, 1, "left over"); + assert!(until_window(&mut app)); + assert_eq!(title(&app), "B", "the second dialog's title"); + assert_eq!(typed(&app, 1), None, "without the first dialog's typed text"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, "y"]])); +} + +#[test] +fn a_dialog_function_after_show_opens_its_own_dialog() { + let mut app = app(); + start(&mut app, &format!("{FORM} w.show(); alert('done');")); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + for _ in 0..100 { + script_runs::poll(&mut app); + if is_open::(&app) { + break; + } + } + assert!(is_open::(&app), "the alert opens"); + assert!(!is_open::(&app), "the dialog its show() ended is closed"); + assert!(app.session.script_dialog().is_some()); +} + +#[test] +fn an_alert_from_a_handler_ends_the_run_and_closes_the_dialog() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var e = w.add('edittext', undefined, 'a'); var b = w.add('button', undefined, 'Tell'); \ + b.onClick = function () { alert('told'); }; w.add('button', undefined, 'OK'); vc.log([w.show(), e.text]);", + ); + assert!(until_window(&mut app)); + type_text(&app, 1, "typed"); + give(&mut app, json!({"event": "click", "control": "Tell"})).unwrap(); + assert!(until_window(&mut app), "the script takes the typed text first"); + step(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the handler's alert ends the run"); + let report = app.session.script_report().unwrap(); + assert!(report["message"].as_str().is_some_and(|m| m.contains("alert: a dialog cannot open inside a callback")), "{report}"); + assert!(!is_open::(&app) && !is_open::(&app), "no dialog of the run stays open"); + step(&mut app, Vec::new()); + assert!(!crate::dialogs::script_run::busy(&app), "the next frame takes down the dialog's window"); +} + +#[test] +fn stop_in_the_dialog_rolls_the_run_back() { + let mut app = app(); + start(&mut app, &format!("{DRAW} {FORM} w.show(); vc.log('after');")); + assert!(until_window(&mut app)); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); + assert_eq!(objects(&app), 0); + assert_eq!(app.session.script_report().unwrap()["dialogs"][0]["answer"], "stop"); + assert!(!is_open::(&app)); +} + +#[test] +fn quitting_while_the_dialog_waits_asks_and_cancel_shows_it_again() { + let mut app = app(); + start(&mut app, &format!("{DRAW} {FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + type_text(&app, 1, "typed"); + crate::dialogs::script_run::ask_to_close(&mut app); + assert!(is_open::(&app)); + cancel_close_question(&mut app); + assert!(until_window(&mut app), "the dialog shows again"); + assert_eq!(typed(&app, 1).as_deref(), Some("typed"), "with the text typed in its field"); + crate::dialogs::script_run::ask_to_close(&mut app); + assert!(super::script_dialogs::confirm(&mut app, CLOSE_KIND)); + assert!(!app.session.script_running()); + assert_eq!(objects(&app), 0); + assert!(!is_open::(&app)); +} + +#[test] +fn quitting_while_a_handler_runs_keeps_the_events_still_queued() { + let mut app = app(); + start(&mut app, &format!("{DRAW} {FORM} name.onChange = function () {{ name.text = name.text + '!'; }}; vc.log([w.show(), name.text]);")); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "change", "control": "name", "value": "Ann"})).unwrap(); + with_window(&app, |d| d.queue(&UiEvent::Click(3))).unwrap(); + crate::dialogs::script_run::ask_to_close(&mut app); + assert!(is_open::(&app)); + script_runs::poll(&mut app); + cancel_close_question(&mut app); + assert!(until_window(&mut app), "the dialog shows again"); + assert!(!queued(&app).is_empty(), "with the click still queued"); + step(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([[1, "Ann!"]])); +} + +#[test] +fn a_click_from_ui_dialog_confirm_gives_the_typed_text_first() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log([w.show(), name.text]);")); + assert!(until_window(&mut app)); + type_text(&app, 1, "typed"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(until_window(&mut app), "the script takes the text and waits again"); + assert_eq!(typed(&app, 1), None, "the text is given once"); + step(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([[1, "typed"]])); +} + +#[test] +fn a_typed_text_the_script_refuses_keeps_every_field_and_queues_nothing() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); w.add('edittext', undefined, 'a'); w.add('edittext', undefined, 'b'); \ + w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel'); vc.log(w.show());", + ); + assert!(until_window(&mut app)); + let long = "x".repeat(16 * 1024 + 1); + type_text(&app, 1, &long); + type_text(&app, 2, "fine"); + let kept = |app: &VectorcraftApp| { + assert!(is_open::(app), "the dialog stays open"); + assert_eq!(typed(app, 1).as_deref(), Some(long.as_str()), "the refused text stays in its field"); + assert_eq!(typed(app, 2).as_deref(), Some("fine"), "and so does the other one"); + assert!(queued(app).is_empty(), "nothing is queued"); + }; + assert!(give(&mut app, json!({"event": "click", "control": "OK"})).is_err(), "OK is an error"); + kept(&app); + assert!(script_window::cancel(&mut app).is_err(), "Cancel is an error"); + kept(&app); + let ctx = app.ui_ctx.clone().unwrap(); + for (method, params) in [("ui.dialog.cancel", json!({})), ("ui.dialog.set", json!({"fields": [], "action": "cancel"}))] { + let (req, _) = ControlRequest::new(method, params); + let Reply::Done(r) = crate::control::handle(&mut app, &ctx, &req) else { panic!("{method}: not done") }; + assert_eq!(r["ok"], false, "{method} answers with the error: {r}"); + kept(&app); + } + assert!(app.session.script_window().is_some(), "the script still waits"); + type_text(&app, 1, "a"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(until_window(&mut app), "the script takes the other text and waits again"); + assert_eq!(app.session.script_window().unwrap().nodes[2].text, "fine"); + step(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([1])); +} + +#[test] +fn a_typed_text_the_script_refuses_stays_in_its_field_after_it_loses_the_focus() { + let mut app = app(); + start(&mut app, "var w = new Window('dialog'); w.add('edittext', undefined, 'a'); w.add('button', undefined, 'OK'); vc.log(w.show());"); + assert!(until_window(&mut app)); + let long = "x".repeat(16 * 1024 + 1); + with_window(&app, |d| { + let mut events = vec![UiEvent::Change(1, UiValue::Text(long.clone())), UiEvent::Change(1, UiValue::Text("fine".into()))]; + assert!(d.keep_refused_texts(&mut events).is_some(), "the long text is an error"); + assert_eq!(events, vec![UiEvent::Change(1, UiValue::Text("fine".into()))], "a text the script takes is still given"); + }) + .unwrap(); + assert_eq!(typed(&app, 1).as_deref(), Some(long.as_str()), "the refused text goes back in its field"); + frame(&app, Vec::new()); + frame(&app, Vec::new()); + assert_eq!(typed(&app, 1).as_deref(), Some(long.as_str()), "and stays there while the field has no focus"); + assert!(app.session.script_window().is_some(), "the script still waits"); + assert!(give(&mut app, json!({"event": "click", "control": "OK"})).is_err(), "OK is an error until it is fixed"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +/// One pass of the dialog host with accessibility on, drawn as part of the window. → what the pass +/// gave. +fn access_frame(app: &mut VectorcraftApp) -> egui::FullOutput { + let ctx = app.ui_ctx.clone().unwrap(); + ctx.enable_accesskit(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + crate::testing::part_frame(app, &ctx, egui::RawInput { screen_rect, ..Default::default() }, |app, ui| { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + }) +} + +/// One pass of the dialog host with accessibility on. → the nodes it reports. +fn access_nodes(app: &mut VectorcraftApp) -> Vec<(egui::accesskit::NodeId, egui::accesskit::Node)> { + access_frame(app).platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() +} + +#[test] +fn a_typed_text_the_script_refuses_stays_in_its_field_when_a_click_on_a_button_takes_the_focus() { + let mut app = app(); + start(&mut app, "var w = new Window('dialog'); w.add('edittext', undefined, 'a'); w.add('button', undefined, 'OK'); vc.log(w.show());"); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + access_nodes(&mut app); + let nodes = access_nodes(&mut app); + let center = |found: Option<&egui::accesskit::Node>, what: &str| { + let b = found.and_then(egui::accesskit::Node::bounds).unwrap_or_else(|| panic!("no {what}")); + egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5) + }; + let field = center(nodes.iter().map(|(_, n)| n).find(|n| n.role() == egui::accesskit::Role::TextInput), "edit field"); + let ok = center(nodes.iter().map(|(_, n)| n).find(|n| n.role() == egui::accesskit::Role::Button && n.label() == Some("OK")), "OK button"); + let click = |app: &mut VectorcraftApp, at: egui::Pos2| { + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + step(app, vec![egui::Event::PointerMoved(at)]); + step(app, vec![button(true)]); + step(app, vec![button(false)]); + }; + click(&mut app, field); + let long = "x".repeat(16 * 1024 + 1); + step(&mut app, vec![egui::Event::Text(long.clone())]); + let typed_now = typed(&app, 1).expect("the typed text is kept while the field has the focus"); + assert!(typed_now.len() > 16 * 1024 && typed_now.contains(&long), "the field holds the long text"); + click(&mut app, ok); + step(&mut app, Vec::new()); + assert!(is_open::(&app), "the dialog stays open"); + assert_eq!(typed(&app, 1), Some(typed_now), "the refused text stays in its field"); + assert!(queued(&app).is_empty(), "nothing is queued"); + assert!(app.ui.status.contains("16 KiB"), "the error is in the status bar: {}", app.ui.status); + assert!(app.session.script_window().is_some(), "the script still waits"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +#[test] +fn screen_readers_read_a_group_by_its_name() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var g = w.add('group', undefined, {name: 'opts'}); g.add('checkbox', undefined, 'Bold'); vc.log(w.show());", + ); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + access_nodes(&mut app); + let nodes = access_nodes(&mut app); + let group = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::Group && n.label() == Some("opts")); + let (group, _) = group.unwrap_or_else(|| panic!("the group is in the accessibility tree")); + let bold = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::CheckBox && n.label() == Some("Bold")); + let (bold, _) = bold.unwrap_or_else(|| panic!("no Bold check box")); + let parent_of = |id: egui::accesskit::NodeId| nodes.iter().find(|(_, n)| n.children().contains(&id)).map(|(p, _)| *p); + let mut at = Some(*bold); + let mut inside = false; + for _ in 0..16 { + at = at.and_then(parent_of); + if at == Some(*group) { + inside = true; + break; + } + } + assert!(inside, "the check box is inside the group in the accessibility tree"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +#[test] +fn an_edit_field_takes_at_most_its_draft_limit_while_it_is_typed() { + let mut app = app(); + start(&mut app, "var w = new Window('dialog'); w.add('edittext', undefined, ''); w.add('button', undefined, 'OK'); vc.log(w.show());"); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + access_nodes(&mut app); + let nodes = access_nodes(&mut app); + let b = nodes.iter().map(|(_, n)| n).find(|n| n.role() == egui::accesskit::Role::TextInput).and_then(egui::accesskit::Node::bounds); + let b = b.unwrap_or_else(|| panic!("no edit field")); + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + step(&mut app, vec![egui::Event::PointerMoved(at)]); + step(&mut app, vec![button(true)]); + step(&mut app, vec![button(false)]); + step(&mut app, vec![egui::Event::Paste("x".repeat(script_window::DRAFT_CHARS + 100))]); + let typed_now = typed(&app, 1).expect("the pasted text is kept while the field has the focus"); + assert_eq!(typed_now.chars().count(), script_window::DRAFT_CHARS, "the draft stops at its limit"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +#[test] +fn a_queued_click_reaches_its_button_after_a_handler_adds_a_control_before_it() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var p = w.add('panel'); var e = w.add('edittext', undefined, 'a'); w.add('button', undefined, 'OK'); \ + e.onChange = function () { p.add('statictext', undefined, 'Added'); }; vc.log([w.show(), e.text]);", + ); + assert!(until_window(&mut app)); + type_text(&app, 2, "typed"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(until_window(&mut app), "the script takes the text and waits again"); + assert_eq!(app.session.script_window().unwrap().nodes[4].text, "OK", "the handler added a control before OK"); + step(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([[1, "typed"]])); +} + +/// Polls the run until the question about its growth opens. +fn until_growth(app: &mut VectorcraftApp) { + for _ in 0..10_000 { + if is_open::(app) { + return; + } + assert!(app.session.script_running(), "the run asks about its growth"); + script_runs::poll(app); + } + panic!("the run did not ask about its growth"); +} + +#[test] +fn continue_on_the_growth_question_shows_the_dialog_again_with_its_queued_click_and_typed_text() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var e = w.add('edittext', undefined, 'a'); var g = w.add('button', undefined, 'Grow'); \ + w.add('button', undefined, 'OK'); g.onClick = function () { vc.run('shape.rectangle', {x:0,y:0,width:10,height:10}); \ + for (var k = 0; k < 17; k++) { vc.run('select.all'); vc.run('edit.duplicate'); } }; vc.log([w.show(), e.text]);", + ); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "Grow"})).unwrap(); + type_text(&app, 1, "typed"); + with_window(&app, |d| d.queue(&UiEvent::Click(3))).unwrap(); + until_growth(&mut app); + assert!(is_open::(&app), "the question opens over the dialog"); + assert_eq!(typed(&app, 1).as_deref(), Some("typed"), "the text typed in its field waits under the question"); + // Enter goes to the question over the dialog, whose default is Continue, and clicks nothing + // in the dialog under it. + frame(&app, Vec::new()); + frame(&app, vec![key(egui::Key::Enter)]); + assert!(!is_open::(&app), "Enter answers the question"); + assert_eq!(queued(&app), vec![Queued::Click(4)], "the dialog under it takes no click from Enter"); + pump(&mut app); + assert!(is_open::(&app), "Continue shows the dialog again"); + // The run waits at its dialog again, takes the typed text, then the queued click on OK. + run_to_end(&mut app); + assert_eq!(log(&app), json!([[1, "typed"]])); +} + +/// Takes the run through the events its dialog has queued, one wait at a time, to its end. +fn run_to_end(app: &mut VectorcraftApp) { + for _ in 0..8 { + if !until_window(app) { + return; + } + step(app, Vec::new()); + } + panic!("the run did not end with the events its dialog had queued"); +} + +#[test] +fn a_typed_text_stays_with_its_field_after_a_handler_adds_a_control_before_it_and_the_run_grows() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var p = w.add('panel'); var e = w.add('edittext', undefined, 'a'); \ + var g = w.add('button', undefined, 'Grow'); w.add('button', undefined, 'OK'); g.onClick = function () { \ + p.add('statictext', undefined, 'Added'); vc.run('shape.rectangle', {x:0,y:0,width:10,height:10}); \ + for (var k = 0; k < 17; k++) { vc.run('select.all'); vc.run('edit.duplicate'); } }; vc.log([w.show(), e.text]);", + ); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + give(&mut app, json!({"event": "click", "control": "Grow"})).unwrap(); + type_text(&app, 2, "typed"); + with_window(&app, |d| d.queue(&UiEvent::Click(4))).unwrap(); + step(&mut app, Vec::new()); + until_growth(&mut app); + assert!(super::script_dialogs::confirm(&mut app, GROWTH_KIND)); + assert!(until_window(&mut app), "the script waits at its dialog again"); + let w = app.session.script_window().unwrap(); + assert_eq!(w.nodes[2].text, "Added", "the handler added a control before the edit field"); + assert_eq!((w.nodes[3].kind, w.nodes[3].text.as_str()), (UiKind::EditText, "typed"), "the typed text reached its field, now one place later"); + run_to_end(&mut app); + assert_eq!(log(&app), json!([[1, "typed"]])); +} + +#[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)); + give(&mut app, json!({"event": "click", "control": "x"})).unwrap(); + with_window(&app, |d| { + d.queue(&UiEvent::Click(2)); + d.queue(&UiEvent::Click(3)); + }) + .unwrap(); + 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"); + step(&mut app, Vec::new()); + assert!(until_window(&mut app), "the script runs y's handler and waits again"); + assert!(queued(&app).is_empty(), "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_click_from_ui_dialog_confirm_waits_behind_the_events_still_queued() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var g = w.add('group'); var x = g.add('button', undefined, 'x'); var y = g.add('button', undefined, 'y'); \ + var hit = []; x.onClick = function () { hit.push('x'); }; y.onClick = function () { hit.push('y'); w.close(); }; \ + vc.log([w.show(), hit]);", + ); + assert!(until_window(&mut app)); + let ids: Vec = app.session.script_window().unwrap().nodes.iter().map(|n| n.id).collect(); + with_window(&app, |d| d.queue(&UiEvent::Click(2))).unwrap(); + give(&mut app, json!({"event": "click", "control": "y"})).unwrap(); + assert_eq!(queued(&app), vec![Queued::Click(ids[2]), Queued::Click(ids[3])], "the confirmed click goes after the queued one"); + run_to_end(&mut app); + assert_eq!(log(&app)[0][1], json!(["x", "y"]), "the handlers ran in the order the clicks were made"); +} + +#[test] +fn a_queued_list_change_is_dropped_after_a_handler_removes_an_item() { + let mut app = app(); + 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)); + give(&mut app, json!({"event": "click", "control": "Remove"})).unwrap(); + with_window(&app, |d| d.queue(&UiEvent::Change(2, UiValue::Index(Some(1))))).unwrap(); + assert!(until_window(&mut app), "the script runs the handler and waits again"); + step(&mut app, Vec::new()); + assert!(queued(&app).is_empty(), "the change 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 a_queued_list_change_is_dropped_after_a_handler_replaces_the_item_with_one_of_the_same_text() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var rm = w.add('button', undefined, 'Replace'); var l = w.add('listbox', undefined, ['a', 'b', 'c']); \ + rm.onClick = function () { l.remove(2); l.add('item', 'c'); }; vc.log([w.show(), l.selection === null]);", + ); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "Replace"})).unwrap(); + with_window(&app, |d| d.queue(&UiEvent::Change(2, UiValue::Index(Some(2))))).unwrap(); + assert!(until_window(&mut app), "the script runs the handler and waits again"); + step(&mut app, Vec::new()); + assert!(queued(&app).is_empty(), "the change chose the item that was replaced, so it is dropped"); + assert_eq!(app.session.script_window().unwrap().nodes[2].selection, None); + give(&mut app, json!({"event": "close"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[0, true]])); +} + +#[test] +fn cancel_on_the_quit_question_does_not_show_a_dialog_whose_show_ended() { + let mut app = app(); + start( + &mut app, + "var a = new Window('dialog', 'A'); a.add('button', undefined, 'OK'); a.show(); \ + var b = new Window('dialog', 'B'); b.add('button', undefined, 'OK'); vc.log(b.show());", + ); + assert!(until_window(&mut app)); + let first = app.session.script_window().unwrap().shown; + crate::dialogs::script_run::ask_to_close(&mut app); + assert!(is_open::(&app)); + app.session.script_window_answer(UiEvent::Click(1)).unwrap(); + for _ in 0..10_000 { + if app.session.script_window().is_some_and(|w| w.shown != first) { + break; + } + script_runs::poll(&mut app); + } + assert_eq!(app.session.script_window().map(|w| w.title().to_string()), Some("B".to_string()), "the run waits at the second show()"); + crate::dialogs::script_run::settle_close(&mut app); + assert!(is_open::(&app)); + let open = with_host(&app, |host, _| host.open_dialogs()).unwrap(); + let question = open.iter().find(|d| d.key.as_deref() == Some(CLOSE_KIND)).unwrap(); + assert_eq!(question.parent, None, "the first dialog is forgotten"); + assert!(!is_open::(&app)); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +#[test] +fn ui_dialog_confirm_takes_a_whole_float_as_a_list_index_and_refuses_a_fraction() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var l = w.add('dropdownlist', undefined, ['a', 'b'], {name: 'pick'}); w.add('button', undefined, 'OK'); \ + vc.log([w.show(), l.selection.text]);", + ); + assert!(until_window(&mut app)); + assert!(give(&mut app, json!({"event": "change", "control": "pick", "value": 1.5})).is_err()); + give(&mut app, json!({"event": "change", "control": "pick", "value": 1.0})).unwrap(); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, "b"]])); +} + +#[test] +fn ui_dialog_set_with_an_action_gives_the_event() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log([w.show(), name.text]);")); + assert!(until_window(&mut app)); + let ctx = app.ui_ctx.clone().unwrap(); + let run = |app: &mut VectorcraftApp, method: &str, params: Value| { + let (req, _) = ControlRequest::new(method, params); + let Reply::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("{method}: not done") }; + r + }; + let fields = json!({"fields": [{"field": "event", "value": "change"}, {"field": "control", "value": "name"}, {"field": "value", "value": "Ann"}], "action": "confirm"}); + let r = run(&mut app, "ui.dialog.set", fields); + assert_eq!(r["ok"], true, "{r}"); + assert!(until_window(&mut app)); + let r = run(&mut app, "ui.dialog.set", json!({"field": "title", "value": "x"})); + assert_eq!(r["ok"], false, "the title is read only: {r}"); + let r = run(&mut app, "ui.dialog.set", json!({"field": "event", "value": "click", "action": "wave"})); + assert_eq!(r["ok"], false, "{r}"); + assert_eq!(with_window(&app, |d| d.json_fields().unwrap()["event"].clone()), Some(Value::Null), "a refused action sets no field"); + run(&mut app, "ui.dialog.set", json!({"fields": [{"field": "event", "value": "click"}, {"field": "control", "value": "OK"}]})); + let r = run(&mut app, "ui.dialog.confirm", json!({})); + assert_eq!(r["ok"], true, "{r}"); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, "Ann"]])); +} + +#[test] +fn an_unnamed_edit_field_is_called_by_the_static_text_before_it() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var g = w.add('group'); g.add('statictext', undefined, 'Width:'); g.add('edittext', undefined, '5'); \ + w.add('edittext', undefined, 'x', {name: 'height'}); w.add('edittext', undefined, 'y'); \ + var h = w.add('statictext', undefined, 'Secret'); h.visible = false; w.add('edittext', undefined, 'z'); \ + w.add('statictext', undefined, 'Account'); w.add('edittext', undefined, 'a', {name: 'user'}); w.add('button', undefined, 'OK'); w.show();", + ); + assert!(until_window(&mut app)); + let w = app.session.script_window().unwrap(); + let name = |i: usize| script_window::screen_reader_name(&w.nodes[i], script_window::prompt_of(&w, i)); + assert_eq!(name(3), "Width:", "the static text before it in its group"); + assert_eq!(name(4), "height", "the name the script gave it"); + assert_eq!(name(5), "Text", "the control before it is no static text, and the script gave it no name"); + assert_eq!(name(7), "Text", "a hidden static text is no prompt"); + assert_eq!(name(9), "Account", "the visible text before it goes before the name the script gave"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +#[test] +fn a_title_a_handler_changes_and_a_list_box_reach_the_dialog() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog', 'First'); w.add('statictext', undefined, 'Fruit:'); var l = w.add('listbox', undefined, ['apple', 'pear']); \ + l.selection = 1; w.add('statictext', undefined, 'Size:'); w.add('dropdownlist', undefined, ['small', 'large']); \ + var b = w.add('button', undefined, 'Rename'); b.onClick = function () { w.text = 'Renamed'; }; \ + w.add('button', undefined, 'OK'); w.show();", + ); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "Rename"})).unwrap(); + assert!(until_window(&mut app)); + assert_eq!(title(&app), "Renamed", "the heading follows the handler's title"); + access_nodes(&mut app); + let nodes = access_nodes(&mut app); + let list = nodes.iter().any(|(_, n)| n.role() == egui::accesskit::Role::ListBox && n.label() == Some("Fruit:")); + assert!(list, "screen readers read the list box by its prompt"); + let pear = nodes.iter().any(|(_, n)| n.label() == Some("pear") && n.is_selected() == Some(true)); + assert!(pear, "with its selected item"); + let drop = nodes.iter().any(|(_, n)| n.role() == egui::accesskit::Role::ComboBox && n.label() == Some("Size:")); + assert!(drop, "screen readers read the drop-down list by its prompt"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +#[test] +fn an_arrow_key_and_a_click_in_a_list_box_give_the_script_the_change() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['apple', 'pear', 'plum']); l.selection = 0; \ + var picked = []; l.onChange = function () { picked.push(l.selection.index); }; \ + w.add('button', undefined, 'OK'); vc.log([w.show(), picked]);", + ); + assert!(until_window(&mut app)); + let mut on_list = false; + for _ in 0..8 { + step(&mut app, vec![key(egui::Key::Tab)]); + let out = access_frame(&mut app); + on_list = out.platform_output.accesskit_update.is_some_and(|u| { + u.nodes.iter().any(|(id, n)| *id == u.focus && matches!(n.role(), egui::accesskit::Role::ListBox | egui::accesskit::Role::ListItem)) + }); + if on_list { + break; + } + } + assert!(on_list, "Tab puts the focus on the list box"); + step(&mut app, vec![key(egui::Key::ArrowDown)]); + assert!(until_window(&mut app), "the change handler runs and the dialog waits again"); + step(&mut app, Vec::new()); + access_nodes(&mut app); + let nodes = access_nodes(&mut app); + let bounds = |role: egui::accesskit::Role, label: Option<&str>| { + nodes + .iter() + .map(|(_, n)| n) + .find(|n| n.role() == role && (label.is_none() || n.label() == label)) + .and_then(egui::accesskit::Node::bounds) + .unwrap_or_else(|| panic!("no {role:?} {label:?}")) + }; + let (list, ok) = (bounds(egui::accesskit::Role::ListBox, None), bounds(egui::accesskit::Role::Button, Some("OK"))); + assert!(list.y1 <= ok.y0, "the list box ends above the OK button below it: {list:?} {ok:?}"); + let b = bounds(egui::accesskit::Role::ListItem, Some("apple")); + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, ((b.y0 + b.y1) * 0.5) as f32); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + step(&mut app, vec![egui::Event::PointerMoved(at)]); + step(&mut app, vec![button(true)]); + step(&mut app, vec![button(false)]); + assert!(until_window(&mut app), "the change handler runs again"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, [1, 0]]]), "the arrow key picked pear, the click picked apple, and the script was told each time"); +} + +#[test] +fn a_click_on_a_list_box_row_gives_the_list_the_keyboard_focus() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['apple', 'pear', 'plum']); l.selection = 0; \ + var picked = []; l.onChange = function () { picked.push(l.selection.index); }; \ + w.add('button', undefined, 'OK'); vc.log([w.show(), picked]);", + ); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + access_nodes(&mut app); + let nodes = access_nodes(&mut app); + let b = nodes + .iter() + .map(|(_, n)| n) + .find(|n| n.role() == egui::accesskit::Role::ListItem && n.label() == Some("pear")) + .and_then(egui::accesskit::Node::bounds) + .unwrap_or_else(|| panic!("no pear row")); + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, ((b.y0 + b.y1) * 0.5) as f32); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + step(&mut app, vec![egui::Event::PointerMoved(at)]); + step(&mut app, vec![button(true)]); + step(&mut app, vec![button(false)]); + assert!(until_window(&mut app), "the change handler runs"); + step(&mut app, vec![key(egui::Key::ArrowDown)]); + assert!(until_window(&mut app), "the change handler runs again"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, [1, 2]]]), "the click picked pear, and the arrow key went on from it to plum"); +} + +#[test] +fn controls_are_drawn_at_the_size_the_script_gave_them() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); w.add('button', undefined, 'Wide').preferredSize = [240, 60]; var e = w.add('edittext', undefined, 'a'); \ + e.preferredSize = [200, -1]; w.add('checkbox', undefined, 'Remember the size'); w.add('button', undefined, 'OK'); vc.log(w.show());", + ); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + access_nodes(&mut app); + let nodes = access_nodes(&mut app); + let bounds = |role: egui::accesskit::Role, label: Option<&str>| { + nodes + .iter() + .map(|(_, n)| n) + .find(|n| n.role() == role && (label.is_none() || n.label() == label)) + .and_then(egui::accesskit::Node::bounds) + .unwrap_or_else(|| panic!("no {role:?} {label:?}")) + }; + let w = app.session.script_window().unwrap(); + let (wide, ok, field) = ( + bounds(egui::accesskit::Role::Button, Some("Wide")), + bounds(egui::accesskit::Role::Button, Some("OK")), + bounds(egui::accesskit::Role::TextInput, None), + ); + assert!(wide.width() > ok.width() && wide.height() > ok.height(), "the wide button is larger than OK: {wide:?} {ok:?}"); + assert!((wide.width() - f64::from(w.nodes[1].rect.w)).abs() < 1.0, "the wide button is as wide as its preferred size: {wide:?}"); + assert!((field.width() - f64::from(w.nodes[2].rect.w)).abs() < 1.0, "the field is as wide as its preferred size: {field:?}"); + let (check, caption) = (bounds(egui::accesskit::Role::CheckBox, None), bounds(egui::accesskit::Role::Label, Some("Remember the size"))); + assert!( + caption.x0 >= check.x1 && caption.y0 < check.y1 && caption.y1 > check.y0, + "the check box shows its text after the box: {check:?} {caption:?}" + ); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +#[test] +fn the_run_asks_its_question_over_the_dialog_only_while_no_popup_is_open_over_it() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); w.add('statictext', undefined, 'Size:'); w.add('dropdownlist', undefined, ['small', 'large']); \ + w.add('button', undefined, 'OK'); vc.log(w.show());", + ); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + assert!(crate::dialogs::script_run::can_ask(&app), "the question can open over the dialog alone"); + access_nodes(&mut app); + let nodes = access_nodes(&mut app); + let b = nodes + .iter() + .map(|(_, n)| n) + .find(|n| n.role() == egui::accesskit::Role::ComboBox && n.label() == Some("Size:")) + .and_then(egui::accesskit::Node::bounds) + .unwrap_or_else(|| panic!("no drop-down list")); + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, ((b.y0 + b.y1) * 0.5) as f32); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + step(&mut app, vec![egui::Event::PointerMoved(at)]); + step(&mut app, vec![button(true)]); + step(&mut app, vec![button(false)]); + step(&mut app, Vec::new()); + assert!(script_window::is_top(&app), "no dialog is open over it"); + assert!(!crate::dialogs::script_run::can_ask(&app), "the drop-down list's popup is open over the dialog"); + step(&mut app, vec![key(egui::Key::Escape)]); + step(&mut app, Vec::new()); + assert!(crate::dialogs::script_run::can_ask(&app), "the popup closed"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +#[test] +fn queued_events_wait_while_the_quit_question_is_open_over_the_dialog() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log([w.show(), name.text]);")); + assert!(until_window(&mut app)); + with_window(&app, |d| d.queue(&UiEvent::Click(3))).unwrap(); + crate::dialogs::script_run::ask_to_close(&mut app); + assert!(is_open::(&app)); + for _ in 0..4 { + step(&mut app, Vec::new()); + script_runs::poll(&mut app); + } + assert!(app.session.script_running(), "the run waits while the question is open"); + assert_eq!(queued(&app).len(), 1, "the click stays queued"); + cancel_close_question(&mut app); + step(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog once the question is answered"); + assert_eq!(log(&app), json!([[1, "first"]])); +} + +#[test] +fn ui_dialog_requests_on_the_script_dialog_are_checked_as_on_other_dialogs() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log([w.show(), name.text]);")); + assert!(until_window(&mut app)); + let ctx = app.ui_ctx.clone().unwrap(); + let run = |app: &mut VectorcraftApp, method: &str, params: Value| { + let (req, _) = ControlRequest::new(method, params); + let Reply::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("{method}: not done") }; + r + }; + run(&mut app, "ui.dialog.set", json!({"field": "event", "value": "close"})); + // Confirm and cancel take only the dialog, and give nothing when asked with more. + let r = run(&mut app, "ui.dialog.confirm", json!({"field": "event", "value": "click"})); + assert_eq!(r["ok"], false, "{r}"); + let r = run(&mut app, "ui.dialog.cancel", json!({"value": 1})); + assert_eq!(r["ok"], false, "{r}"); + // A set names a field, or an action. + let r = run(&mut app, "ui.dialog.set", json!({})); + assert_eq!(r["ok"], false, "{r}"); + assert!(app.session.script_window().is_some(), "the refused requests gave the script nothing"); + // A set answers with the dialog it set. + let r = run(&mut app, "ui.dialog.set", json!({"field": "event", "value": "close"})); + assert_eq!(r["result"]["key"], KIND, "{r}"); + assert_eq!(r["result"]["fields"]["event"], "close", "{r}"); + // A dialog open over it takes its answer first. + crate::dialogs::script_run::ask_to_close(&mut app); + let id = open_id(&app, KIND).value().to_string(); + let r = run(&mut app, "ui.dialog.confirm", json!({"dialog": id})); + assert_eq!(r["ok"], false, "{r}"); + let r = run(&mut app, "ui.dialog.set", json!({"dialog": id, "action": "confirm"})); + assert_eq!(r["ok"], false, "{r}"); + assert!(app.session.script_window().is_some(), "the script still waits at its dialog"); + cancel_close_question(&mut app); + let r = run(&mut app, "ui.dialog.confirm", json!({})); + assert_eq!(r["ok"], true, "{r}"); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[0, "first"]])); +} + +#[test] +fn a_cancel_after_a_typed_text_clicks_the_cancel_button_the_dialog_has_when_its_turn_comes() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var e = w.add('edittext', undefined, 'a'); var c = w.add('button', undefined, 'Cancel'); \ + e.onChange = function () { c.enabled = false; }; vc.log([w.show(), e.text]);", + ); + assert!(until_window(&mut app)); + type_text(&app, 1, "typed"); + script_window::cancel(&mut app).unwrap(); + assert_eq!(queued(&app), vec![Queued::Cancel], "the cancel waits for the typed text"); + run_to_end(&mut app); + assert_eq!(log(&app), json!([[0, "typed"]]), "the disabled Cancel button is passed over for the close box"); +} + +#[test] +fn enter_with_the_focus_on_a_slider_clicks_the_default_button() { + let mut app = app(); + start(&mut app, "var w = new Window('dialog'); w.add('slider', undefined, 2, 0, 5); w.add('button', undefined, 'OK'); vc.log(w.show());"); + assert!(until_window(&mut app)); + let mut on_slider = false; + for _ in 0..8 { + step(&mut app, vec![key(egui::Key::Tab)]); + let out = access_frame(&mut app); + on_slider = out + .platform_output + .accesskit_update + .is_some_and(|u| u.nodes.iter().any(|(id, n)| *id == u.focus && n.role() == egui::accesskit::Role::Slider)); + if on_slider { + break; + } + } + assert!(on_slider, "Tab puts the focus on the slider"); + step(&mut app, vec![key(egui::Key::Enter)]); + assert!(!until_window(&mut app), "Enter clicks OK, which closes the dialog"); + assert_eq!(log(&app), json!([1])); +} + +#[test] +fn the_dialog_closes_when_its_show_ends_and_the_script_runs_on() { + let mut app = app(); + start(&mut app, "var w = new Window('dialog'); w.add('button', undefined, 'OK'); w.show(); while (true) {}"); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + for _ in 0..3 { + script_runs::poll(&mut app); + } + assert!(app.session.script_running(), "the script still runs"); + assert!(!is_open::(&app), "the dialog its show() ended is closed"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +#[test] +fn stop_ends_the_run() { + let mut app = app(); + start(&mut app, &format!("{DRAW} {FORM} w.show();")); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + let nodes = access_nodes(&mut app); + let stop = nodes.iter().map(|(_, n)| n).find(|n| n.role() == egui::accesskit::Role::Button && n.label() == Some("Stop")); + let b = stop.and_then(egui::accesskit::Node::bounds).expect("a Stop button"); + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + step(&mut app, vec![egui::Event::PointerMoved(at)]); + step(&mut app, vec![button(true)]); + step(&mut app, vec![button(false)]); + assert!(!until_window(&mut app)); + assert_eq!(objects(&app), 0, "the run is put back"); + assert!(!is_open::(&app)); +} + +#[test] +fn a_large_dialog_draws_in_a_small_window() { + let mut app = app(); + let source = "var w = new Window('dialog', 'Big'); var p = w.add('panel', undefined, 'Lots'); \ + for (var i = 0; i < 200; i++) p.add('checkbox', undefined, 'Option ' + i); \ + var l = w.add('listbox', undefined, ['a', 'b']); var d = w.add('dropdownlist', undefined, ['x', 'y']); \ + w.add('slider', undefined, 2, 0, 5); w.add('progressbar', undefined, 1, 4); w.add('edittext', undefined, 'm', {multiline: true}); \ + w.add('button', undefined, 'OK'); vc.log(w.show());"; + start(&mut app, source); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + step(&mut app, Vec::new()); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([1])); +} + +#[test] +fn a_close_closes_the_dialog_after_a_click_on_a_control_it_lacks() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + assert!(give(&mut app, json!({"event": "click", "control": "missing"})).is_err()); + // Only `event` changes; `control` still names the missing control. + let id = open_id(&app, KIND); + with_host(&app, |host, ctx| host.set_json_field(ctx, id, "event", json!("close"))).unwrap().unwrap(); + script_window::confirm(&mut app).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([0])); +} + +#[test] +fn a_cancel_while_a_handler_runs_reaches_the_dialog_s_next_wait() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log([w.show(), name.text]);")); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + give(&mut app, json!({"event": "click", "control": "Bold"})).unwrap(); + assert!(app.session.script_window().is_none(), "the click's handler has not run yet"); + script_window::cancel(&mut app).unwrap(); + assert_eq!(queued(&app), vec![Queued::Cancel]); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued cancel clicks Cancel"); + assert_eq!(log(&app), json!([[2, "clicked"]])); +} + +#[test] +fn a_queued_text_the_script_refuses_goes_back_in_its_field() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var name = w.add('edittext', undefined, 'first', {name: 'name'}); \ + var lock = w.add('checkbox', undefined, 'Lock'); lock.onClick = function () { name.enabled = false; }; \ + w.add('button', undefined, 'OK'); vc.log([w.show(), name.text]);", + ); + assert!(until_window(&mut app)); + with_window(&app, |d| { + d.queue(&UiEvent::Click(2)); + d.queue(&UiEvent::Change(1, UiValue::Text("Ann".into()))); + }) + .unwrap(); + step(&mut app, Vec::new()); + assert!(until_window(&mut app), "the click's handler disabled the field"); + step(&mut app, Vec::new()); + assert_eq!(typed(&app, 1).as_deref(), Some("Ann"), "the refused text stays in its field"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, "first"]])); +} diff --git a/docs/mcp.md b/docs/mcp.md index 01a4ead5cf..9470e48724 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3258,10 +3258,12 @@ app's own errors, syntax errors and limits. The status bar shows a `script` mess - `console` is `{lines, droppedLines, truncatedLines}`: the run's own output, `vc.log` lines and uncaught error, as text. - `dialogs` lists the run's dialogs in the order they opened, as `{kind, message, title, errorIcon, answer}` for - `alert`, `{kind, message, title, noAsDefault, answer}` for `confirm` and `{kind, message, title, preset, answer}` - for `prompt`. `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, `"stop"` for a dialog the - run ended at, or `"missing"` for a dialog `answers` had no answer for. `dialogCount` counts every dialog, and - `dialogsTruncated` is true when the list stopped at its limit. + `alert`, `{kind, message, title, noAsDefault, answer}` for `confirm`, `{kind, message, title, preset, answer}` + for `prompt` and `{kind, title, controls, events, answer}` for a ScriptUI dialog's `show()` (kind `window`). + `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, the number `show()` returned, `"stop"` + for a dialog the run ended at, `"missing"` for a dialog `answers` had no answer or no step for, or `"error"` for a + `show()` that ended with an error. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list + stopped at its limit. ```json {"name":"run_command","arguments":{"command":"script.run","params":{"source":"vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"}}} @@ -3312,6 +3314,133 @@ empty object are the same. vectorcraft-cli run --cmd script.run --params '{"source": "if (confirm(\"Add a frame?\")) vc.log(prompt(\"Name\", \"Frame\"));", "answers": [{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "Border"}]}' ``` +The help pages https://extendscript.docsforadobe.dev/user-interface-tools/window-object/, +https://extendscript.docsforadobe.dev/user-interface-tools/control-objects/ and +https://extendscript.docsforadobe.dev/user-interface-tools/types-of-controls/ describe ScriptUI's `Window` and its +controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and shows it: + +- `new Window("dialog"[, title, bounds, properties])` makes a dialog. Another type (`palette`, `window`) throws + an `Error` that says it is not available yet. +- `new Window` and `add` also take a resource specification in place of the type, as + https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/ describes it: + `"dialog { text: 'Settings', g: Group { label: StaticText { text: 'Name:' }, ok: Button { text: 'OK' } } }"`, or + `"[name:] Class { ... }"` for `add`. The other arguments are not read. Inside the braces, `properties` gives the + creation properties, each `name: Class { ... }` adds that control through `add`, with its limits, and sets it as + the container's property `name`, a list's `items` gives its item texts, and every other `name: value` sets that + property. A value is `null`, `true`, `false`, a quoted string, a number, an inline array or an inline object, + and the commas between properties may be left out. A malformed specification throws a `SyntaxError`, and one longer than 1 MiB or nested more than 64 + deep throws a `RangeError` (VectorCraft's own limits). +- `container.add(type[, bounds, ...])` adds a control to the dialog, a `group` or a `panel` and returns it. The + types are `group`, `panel`, `statictext`, `edittext`, `button`, `checkbox`, `radiobutton`, `dropdownlist`, + `listbox`, `slider` and `progressbar`. After `bounds`, a text control takes its text and `properties` (`name`, + 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 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 + unknown type throws too. An `edittext` with `noecho` in its `properties` makes `show()` throw that a field that + hides its text is not available yet, before the dialog opens. +- A list's `add("item", text)` adds an item, `find(text)` gives the first item with that text or `null`, + `remove(what)` removes the item given by its index, the item itself or its text, `removeAll()` removes them all, + `items` lists them and `selection` is the selected item or `null`; setting it to an item or an index selects it. + An item has `text`, `index` and `selected`. +- A control has `text`, `value`, `enabled`, `visible`, `name`, `bounds`, `preferredSize`, `size`, `minimumSize`, + `maximumSize`, `alignment`, `parent`, `window`, `show()`, `hide()` and `notify([event])`. Each size starts as an + object whose `width` and `height` are -1, so a script can set one side, as in `preferredSize.width = 100`; a side + of 0 or less is left to the layout (VectorCraft's own starting values). A container also has `children`, + `orientation` (`row`, `column` or `stack`; a group starts as a row and the dialog and a panel as a column), + `alignChildren`, `spacing` (10 to start), `margins` (15 to start, 0 for a group), `findElement(name)` and + `remove(what)`, which removes the control given by its index, the control itself or its text. Removing an item + or a control that is not there does nothing. 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. +- 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")` 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, 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 + 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, 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 button found by its name or +title counts only while it is enabled and visible. A `show()` inside a handler while a dialog is showing, or of a +dialog that is showing, throws an `Error`. In the app, a `show()` inside a callback of a built-in function, a handler +that `notify` runs included, also throws an `Error`, and so do `alert`, `confirm`, `prompt` and the file dialogs called +from a handler; in a run with nobody to ask, such a `show()` takes a `window` answer, and `alert`, `confirm` and +`prompt` in a handler take their answers from `answers`. A shown dialog can be shown again after it closes. + +`show()` checks the dialog: at most 512 controls, nested at most 16 deep, 1,024 list items in all and 16 KiB of +text a control, past which it throws a `RangeError`, a size or a place that is not a finite number, which throws +too, and a slider's minimum above its maximum. When a getter changes a list's items or an item's text after the +list was read, or adds or removes a control after the controls were read, it reads the dialog again, and throws an +`Error` when the dialog changes again. It lays the controls out from each container's `orientation`, +`alignChildren`, `spacing` and `margins` and each control's `alignment`, `preferredSize` (each side of `size` that +is above 0 takes the place of `preferredSize`'s), `minimumSize`, `maximumSize` and `bounds`, which places it in its +container. A control whose `visible` is false, and every control in it, takes no room in the layout. Sizes and places +are kept within 8,192 pixels. These limits are VectorCraft's own. + +In the app, the dialog (kind `scriptWindow`) draws the controls where they were laid out and has a Stop button, +which ends the run as `script.stop` does. It stays open while one of its handlers runs and closes when `show()` +returns. Enter outside a field clicks the default button, also with the keyboard focus on a slider or another +control that Enter does not click. Escape clicks the +cancel button, or closes the dialog when it has none. Quitting while it waits, or while one of its handlers runs, +asks whether to stop the script, and Cancel shows it again with the events it has not given the script yet. When a +handler takes the run past the growth limit, the question to continue opens over the dialog, and Continue shows the +dialog again with those events and the text typed in its fields. An event that waits for the script goes to the control +it was given to, and a typed text stays in its field, also after a handler adds controls before that one. +`ui.dialog.set` with `event` (`click`, `change` or `close`), `control` (a control's index in the dialog, its name, or +the text of a control without a name) and `value`, then `ui.dialog.confirm`, gives the script that event; a click or a close first gives the +script the text still typed in the dialog's fields. When the dialog holds events the script has not taken yet, the +confirmed event goes after them. When one of those texts is longer than 16 KiB, the script gets +no event and every field keeps its text: `ui.dialog.confirm`, `ui.dialog.cancel` and `ui.dialog.set` with `action` +return an error, and Escape shows it in the status bar. Such a text stays in its field when the field loses the +focus too, with the error in the status bar. A disabled or hidden control, a value out of a list's range, a +list index that is not a whole number and a click on a control that takes none are errors, and the dialog stays +open. + +A run with nobody to ask takes `{kind: "window", value: [step, ...]}` from `answers` for each `show()`. A step is +`{control, event: "click"}`, `{control, event: "change", value}` or `{event: "close"}`, where `control` is a +control's `name`, or the text of a control without a name, and `value` is an edit field's text, a slider's number (kept in its range), or a +list's item index (a whole number, such as `2` or `2.0`) or `null`. The dialog takes the next step each time it +waits. The run ends with an error that the script cannot catch, and every document goes back, when no step is +left, when a step names a control the dialog does not have or that cannot take it, or when the dialog closes, or +an error in a handler ends `show()`, with steps it did not use. + +```sh +vectorcraft-cli run --cmd script.run --params '{"source": "var w = new Window(\"dialog\", \"Frame\"); var name = w.add(\"edittext\", undefined, \"Frame\", {name: \"name\"}); w.add(\"button\", undefined, \"OK\"); w.add(\"button\", undefined, \"Cancel\"); if (w.show() == 1) vc.log(name.text);", "answers": [{"kind": "window", "value": [{"control": "name", "event": "change", "value": "Border"}, {"control": "OK", "event": "click"}]}]}' +``` + The help pages https://extendscript.docsforadobe.dev/file-system-access/file-object/ and https://extendscript.docsforadobe.dev/file-system-access/folder-object/ describe the `File` and `Folder` objects. A script reads files with them: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 72519a66ad..47914823d2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1155,6 +1155,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Custom arrowheads under `--automation-read-root`: `stroke.arrowheads.list` gives `file` as `null` for an arrowheads file outside the read roots and names it by its file name in `error`, and `stroke.arrowheads.edit` and `stroke.arrowheads.reload` refuse such a file before anything is made, opened, brought to the front or read; inside the roots `edit` opens the file under the client's roots. `crates/engine/src/tests/arrowheads.rs` (`an_agent_outside_the_arrowheads_files_folder_sees_its_file_name_alone_and_cannot_reload_it`, `an_agent_edits_the_arrowheads_file_only_inside_its_read_roots`). - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`). - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. + - Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person and runs the controls' `onClick`, `onChanging` and `onChange` handlers. The window's own callbacks are `onShow`, which runs when `show()` starts, and `onClose`, which runs before the dialog closes and keeps it open when it returns false. `show()` returns the result of `close(result)`, or 1 for the default button and 2 for the cancel button when the button has no `onClick` or click listener and no handler closed the dialog with another result. Controls also take `notify`, size objects a script can set one side of, lists' `find` and `remove`, and `addEventListener` for clicks and changes, which the dialog also takes for `show`; `Window.alert`, `Window.confirm` and `Window.prompt` open the script dialogs; a run over MCP or the command line takes the clicks and changes from a `window` answer. `new Window` and `add` also build a window or a control and the controls inside it from a resource specification (https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/). Palettes and other control types throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse. - Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`).