diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index dc33c46ab1..fd02b3a9a1 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, else its text)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar, at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes, windows and resource strings throw that they are not available yet); show() waits like a dialog function, runs onClick, onChanging, onChange, onShow and onClose in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick, or 0 for the close box; a show() inside a handler throws, and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index a674396f4b..4c0ce4a39b 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -23,6 +23,7 @@ use std::rc::Rc; use serde_json::{Map, Value, json}; use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError}; +use super::scriptui::{self, ScriptUiDialog, Showing, UiEvent, UiStep}; use super::{Host, console}; /// The most bytes (UTF-8) of a dialog's message. @@ -48,6 +49,8 @@ pub enum DialogKind { Alert, Confirm, Prompt, + /// A ScriptUI dialog's `show()` ([`super::scriptui`]). + Window, } impl DialogKind { @@ -57,6 +60,7 @@ impl DialogKind { Self::Alert => "alert", Self::Confirm => "confirm", Self::Prompt => "prompt", + Self::Window => "window", } } } @@ -85,6 +89,8 @@ pub enum DialogAnswer { Confirm(bool), /// OK with the field's text, or Cancel (`None`), for `prompt`. Prompt(Option), + /// What happens in a ScriptUI dialog, step by step, for a run with nobody to ask. + Window(Vec), } impl DialogAnswer { @@ -93,13 +99,14 @@ impl DialogAnswer { Self::Ok => DialogKind::Alert, Self::Confirm(_) => DialogKind::Confirm, Self::Prompt(_) => DialogKind::Prompt, + Self::Window(_) => DialogKind::Window, } } /// What the function returns. fn data(&self) -> Data { match self { - Self::Ok => Data::Undefined, + Self::Ok | Self::Window(_) => Data::Undefined, Self::Confirm(b) => Data::Bool(*b), Self::Prompt(Some(t)) => Data::String(t.clone()), Self::Prompt(None) => Data::Null, @@ -112,6 +119,7 @@ impl DialogAnswer { Self::Ok => json!("ok"), Self::Confirm(b) => json!(b), Self::Prompt(t) => json!(t), + Self::Window(steps) => json!(steps.len()), } } } @@ -148,8 +156,9 @@ pub fn cut_to(text: &str, max: usize) -> &str { } /// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value: -/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter -/// took before dialogs existed, is an empty list. +/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "window", value: [step, ...]}` +/// ([`super::scriptui`]). An empty object, which the parameter took before dialogs existed, is an +/// empty list. pub(crate) fn parse_answers(v: Option<&Value>) -> Result, String> { let list = match v { None => return Ok(Vec::new()), @@ -166,11 +175,18 @@ pub(crate) fn parse_answers(v: Option<&Value>) -> Result, Stri list.iter().enumerate().map(|(i, a)| answer(a).map_err(|e| format!("`answers[{i}]` {e}"))).collect() } -fn answer(a: &Value) -> Result { - let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`") }; +fn answer(a: &Value) -> Result { + let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`".into()) }; if o.len() != 2 || !o.contains_key("value") { - return Err("must have exactly `kind` and `value`"); + return Err("must have exactly `kind` and `value`".into()); } + if o.get("kind").and_then(Value::as_str) == Some("window") { + return super::scriptui::parse_steps(&o["value"]).map(DialogAnswer::Window); + } + known_answer(o).map_err(String::from) +} + +fn known_answer(o: &Map) -> Result { match (o.get("kind").and_then(Value::as_str), &o["value"]) { (Some("alert"), Value::String(s)) if s == "ok" => Ok(DialogAnswer::Ok), (Some("alert"), _) => Err("is an alert's answer, whose `value` must be \"ok\""), @@ -180,7 +196,7 @@ fn answer(a: &Value) -> Result { (Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))), (Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"), (Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"), - _ => Err("must have `kind` alert, confirm or prompt"), + _ => Err("must have `kind` alert, confirm, prompt or window"), } } @@ -199,6 +215,12 @@ pub(crate) struct Dialogs { record_bytes: Cell, count: Cell, truncated: Cell, + /// The ScriptUI dialog whose `show()` is running. + window: RefCell>, + /// That dialog waits for what the person does. + window_waiting: Cell, + /// The `show()` calls the run has made. + shows: Cell, } impl Dialogs { @@ -213,6 +235,9 @@ impl Dialogs { record_bytes: Cell::new(0), count: Cell::new(0), truncated: Cell::new(false), + window: RefCell::default(), + window_waiting: Cell::new(false), + shows: Cell::new(0), } } @@ -222,7 +247,118 @@ impl Dialogs { } pub(crate) fn is_waiting(&self) -> bool { - self.waiting.borrow().is_some() + self.waiting.borrow().is_some() || self.window_waiting.get() + } + + /// The ScriptUI dialog that waits for what the person does. + pub(crate) fn waiting_window(&self) -> Option { + if !self.window_waiting.get() { + return None; + } + self.window.borrow().as_ref().map(|s| s.dialog.clone()) + } + + /// Gives the waiting ScriptUI dialog `event`, once it is checked against the dialog. + pub(crate) fn window_answer(&self, realm: &mut Realm, event: UiEvent) -> Result<(), String> { + if !self.window_waiting.get() { + return Err("no script dialog waits".into()); + } + let event = { + let mut window = self.window.borrow_mut(); + let Some(showing) = window.as_mut() else { return Err("no script dialog waits".into()) }; + let event = scriptui::check_event(&showing.dialog, event)?; + showing.events = showing.events.saturating_add(1); + event + }; + self.window_waiting.set(false); + if let Err(e) = realm.answer(event.data()) { + *self.failed.borrow_mut() = Some(e); + } + Ok(()) + } + + fn cannot_wait(&self) -> Result<(), HostError> { + if self.framed && !self.can_wait.get() { + return Err(HostError::Error( + "show: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code" + .into(), + )); + } + Ok(()) + } + + /// `show()` opens `dialog`. A run with nobody to ask takes its next answer, which must be a + /// `window` answer. + pub(crate) fn window_open(&self, mut dialog: ScriptUiDialog) -> Result<(), HostError> { + self.cannot_wait()?; + self.shows.set(self.shows.get().saturating_add(1)); + dialog.shown = self.shows.get(); + let mut showing = Showing { dialog, steps: None, events: 0 }; + if !self.framed { + let next = self.answers.borrow_mut().pop_front(); + match next { + Some(DialogAnswer::Window(steps)) => showing.steps = Some(steps.into()), + Some(a) => { + self.push_record(showing.record(json!("missing"))); + return Err(HostError::Abort(format!("show: the next answer in `answers` is for {}, not window", a.kind().id()))); + } + None => { + self.push_record(showing.record(json!("missing"))); + return Err(HostError::Abort("show: `answers` has no answer left for this dialog".into())); + } + } + } + *self.window.borrow_mut() = Some(showing); + Ok(()) + } + + /// The dialog that is showing waits, as `dialog` now is. A run with nobody to ask takes the + /// next step of its answer. + pub(crate) fn window_wait(&self, mut dialog: ScriptUiDialog) -> Result { + self.cannot_wait()?; + let mut window = self.window.borrow_mut(); + let Some(showing) = window.as_mut() else { return Err(HostError::Error("show: no dialog is showing".into())) }; + dialog.shown = showing.dialog.shown; + showing.dialog = dialog; + let Some(steps) = showing.steps.as_mut() else { + drop(window); + self.window_waiting.set(true); + return Err(HostError::Wait); + }; + let failure = match steps.pop_front() { + None => "show: the dialog's answer in `answers` has no step left".to_string(), + Some(step) => match scriptui::step_event(&showing.dialog, &step) { + Ok(event) => { + showing.events = showing.events.saturating_add(1); + return Ok(event.data()); + } + Err(e) => format!("show: a step of the dialog's answer in `answers` cannot be taken: {e}"), + }, + }; + if let Some(showing) = window.take() { + self.push_record(showing.record(json!("missing"))); + } + Err(HostError::Abort(failure)) + } + + /// `show()` ends with `result`, or with an error when not `normal`. A run with nobody to ask + /// must have used every step of the dialog's answer. + pub(crate) fn window_end(&self, result: f64, normal: bool) -> Result<(), HostError> { + self.window_waiting.set(false); + let Some(showing) = self.window.borrow_mut().take() else { return Ok(()) }; + let left = showing.steps.as_ref().map_or(0, std::collections::VecDeque::len); + if normal && left > 0 { + self.push_record(showing.record(json!("missing"))); + let steps = if left == 1 { "step" } else { "steps" }; + return Err(HostError::Abort(format!("show: the dialog's answer in `answers` has {left} {steps} the dialog did not use"))); + } + let answer = match result { + _ if !normal => json!("error"), + r if r.fract() == 0.0 && r.abs() < 9.0e15 => json!(r as i64), + r => json!(r), + }; + self.push_record(showing.record(answer)); + Ok(()) } /// The error that ended the run when its answer could not reach the script. @@ -257,10 +393,13 @@ impl Dialogs { if let Some(d) = self.waiting.borrow_mut().take() { self.record(&d, json!("stop")); } + self.window_waiting.set(false); + if let Some(showing) = self.window.borrow_mut().take() { + self.push_record(showing.record(json!("stop"))); + } } fn record(&self, d: &ScriptDialog, answer: Value) { - self.count.set(self.count.get().saturating_add(1)); let mut r = Map::new(); r.insert("kind".into(), json!(d.kind.id())); r.insert("message".into(), json!(d.message)); @@ -269,9 +408,14 @@ impl Dialogs { DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)), DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)), DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)), + DialogKind::Window => None, }; r.insert("answer".into(), answer); - let r = Value::Object(r); + self.push_record(Value::Object(r)); + } + + fn push_record(&self, r: Value) { + self.count.set(self.count.get().saturating_add(1)); let bytes = serde_json::to_vec(&r).map_or(usize::MAX, |b| b.len()); let mut records = self.records.borrow_mut(); if self.truncated.get() || records.len() >= MAX_RECORDS || self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES { @@ -325,6 +469,7 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) }; (text(args, 2), false, false, preset) } + DialogKind::Window => return Err(HostError::Error("a ScriptUI dialog opens with show()".into())), }; if message.len() > MAX_MESSAGE_BYTES { return Err(HostError::Range(format!("{name}: the message is longer than 16 KiB"))); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..293d77c716 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -52,8 +52,10 @@ pub mod console; pub mod dialogs; pub mod dollar; pub mod include; +pub mod scriptui; pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog}; +pub use scriptui::{ScriptUiDialog, UiEvent, UiKind, UiValue}; use std::cell::{Cell, RefCell}; use std::collections::HashMap; @@ -133,7 +135,7 @@ impl Written { /// The version `vc.api.version` gives. pub const API_VERSION: &str = "1.0"; /// The features `vc.api.has` knows. -pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar"]; +pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar", "scriptui"]; /// The most commands a run's report lists in `slowestCommands`. pub const SLOWEST_COMMANDS: usize = 5; @@ -1822,6 +1824,23 @@ impl Session { with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false) } + /// The ScriptUI dialog the running script's `show()` waits at for what the person does. A run + /// asked to stop no longer waits: the next [`Session::script_pump`] ends it. + pub fn script_window(&self) -> Option { + if self.script_stop.is_set() { + return None; + } + self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting_window())).flatten() + } + + /// Gives the ScriptUI dialog the running script waits at `event`; the next + /// [`Session::script_pump`] runs the control's handler. → an error, and the dialog still + /// waits, when nothing waits or the dialog cannot take the event ([`scriptui::check_event`]). + pub fn script_window_answer(&mut self, event: UiEvent) -> std::result::Result<(), String> { + let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return Err("no script dialog waits".into()) }; + with_job(k, |j| j.host.dialogs.window_answer(&mut j.realm, event)).unwrap_or_else(|| Err("no script dialog waits".into())) + } + /// The file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects' /// `openDlg`, `saveDlg` and `selectDlg`) the running script waits at. A run asked to stop no /// longer waits. @@ -2076,6 +2095,7 @@ impl Session { .and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) }) .and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) }) .and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) }) + .and_then(|()| if fresh { scriptui::install(&mut realm, &link) } else { Ok(()) }) .and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() }) .and_then(|()| { let r = realm.start(&expanded.source); diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs new file mode 100644 index 0000000000..62cfaade79 --- /dev/null +++ b/crates/engine/src/script/scriptui.rs @@ -0,0 +1,666 @@ +//! ScriptUI dialogs (`new Window("dialog")`, [`vectorcraft_js::scriptui`]): the description a run +//! gives when it shows one, checked and laid out here before the app draws it, and the events the +//! person or `script.run`'s `answers` give back. +//! +//! A description lists the dialog first and each control after the container that holds it. It is +//! refused with an error thrown at `show()` when a control's container comes after it or is not a +//! group or panel, when it holds more than [`MAX_CONTROLS`] controls, nests deeper than +//! [`MAX_DEPTH`], has more than [`MAX_ITEMS`] list items or a text longer than [`MAX_TEXT_BYTES`], +//! names an orientation or an alignment that does not exist, or gives a slider a minimum above its +//! maximum. Sizes, places, spacing and margins are clamped to [`MAX_EXTENT`] pixels, and a slider's +//! or progress bar's value to its range. +//! +//! The layout follows each container's `orientation` (row, column or stack), `alignChildren`, +//! `spacing` and `margins`, a control's `alignment`, `preferredSize` and `bounds` (left, top, right +//! and bottom in its container). A control's size comes from its text, items and kind, by +//! VectorCraft's own estimates of a 7-pixel character and a 16-pixel line. The layout is worked out +//! with loops over the list, from the last control to the first for sizes and from the first to the +//! last for places, so a description's nesting takes no native stack. +//! +//! A run with nobody to ask takes one answer from `answers` for each `show()`: `{kind: "window", +//! value: [step, ...]}`, where a step is `{control, event: "click"}`, `{control, event: "change", +//! value}` or `{event: "close"}`. `control` is a control's `name`, or else its text; `value` is an +//! edit field's text, a slider's number, or a list's item index or `null`. Each time the dialog +//! waits it takes the next step; a dialog that waits with no step left, a step for a control the +//! dialog does not hold or cannot take it, and steps left when the dialog closes end the run. +//! +//! The limits here are VectorCraft's own: [`MAX_EXTENT`], and the js crate's [`MAX_CONTROLS`], +//! [`MAX_DEPTH`], [`MAX_ITEMS`] and [`MAX_TEXT_BYTES`]. + +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; + +pub use vectorcraft_js::scriptui::{MAX_CONTROLS, MAX_DEPTH, MAX_ITEMS, MAX_TEXT_BYTES}; + +use super::Host; + +/// The largest size or place, in pixels, of a dialog or a control in it. +pub const MAX_EXTENT: f32 = 8192.0; +/// A character's width and a line's height in VectorCraft's size estimates, in pixels. +const CHAR: f32 = 7.0; +const LINE: f32 = 16.0; + +/// A dialog's element. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UiKind { + Dialog, + Group, + Panel, + StaticText, + EditText, + Button, + CheckBox, + RadioButton, + DropDownList, + ListBox, + Slider, + ProgressBar, +} + +impl UiKind { + fn parse(s: &str) -> Option { + Some(match s { + "dialog" => Self::Dialog, + "group" => Self::Group, + "panel" => Self::Panel, + "statictext" => Self::StaticText, + "edittext" => Self::EditText, + "button" => Self::Button, + "checkbox" => Self::CheckBox, + "radiobutton" => Self::RadioButton, + "dropdownlist" => Self::DropDownList, + "listbox" => Self::ListBox, + "slider" => Self::Slider, + "progressbar" => Self::ProgressBar, + _ => return None, + }) + } + + /// Does it hold controls? + pub fn container(self) -> bool { + matches!(self, Self::Dialog | Self::Group | Self::Panel) + } + + /// Does a click reach it? + pub fn clicks(self) -> bool { + matches!(self, Self::Button | Self::CheckBox | Self::RadioButton) + } +} + +/// How a container places its controls. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Orientation { + Row, + Column, + Stack, +} + +/// Where a control goes across its container: left or top, right or bottom, the middle, or the +/// whole width or height. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Align { + Start, + End, + Center, + Fill, +} + +/// A control's place and size in the dialog, from its top left corner. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct UiRect { + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, +} + +/// One element of a [`ScriptUiDialog`]. +#[derive(Clone, Debug, PartialEq)] +pub struct UiNode { + pub kind: UiKind, + /// The index of its container; the dialog's own is 0. + pub parent: usize, + pub name: String, + pub text: String, + /// It and every container around it are enabled. + pub enabled: bool, + /// It and every container around it are visible. + pub visible: bool, + /// A check box's or radio button's value. + pub checked: bool, + /// A slider's or progress bar's value, within `min` to `max`. + pub value: f64, + pub min: f64, + pub max: f64, + pub items: Vec, + pub selection: Option, + pub multiline: bool, + pub readonly: bool, + pub rect: UiRect, + orientation: Orientation, + align_children: (Option, Option), + alignment: (Option, Option), + spacing: f32, + margins: [f32; 4], + size: [Option; 2], + bounds: Option, +} + +/// A dialog a run shows, checked and laid out. +#[derive(Clone, Debug, PartialEq)] +pub struct ScriptUiDialog { + /// The dialog first, then each control after the container that holds it. + pub nodes: Vec, + /// The button Enter clicks and the one Escape clicks. + pub default_element: Option, + pub cancel_element: Option, + /// Which `show()` of the run this is, counted from 1; 0 before it shows. + pub shown: u64, +} + +impl ScriptUiDialog { + /// The dialog's title. + pub fn title(&self) -> &str { + self.nodes.first().map_or("", |n| n.text.as_str()) + } + + /// The size of the dialog's content. + pub fn size(&self) -> (f32, f32) { + self.nodes.first().map_or((0.0, 0.0), |n| (n.rect.w, n.rect.h)) + } + + /// The first control whose name, or else whose text, is `control`. + pub fn find(&self, control: &str) -> Option { + let by = |name: bool| { + self.nodes.iter().enumerate().skip(1).find(|(_, n)| if name { n.name == control } else { n.text == control }).map(|(i, _)| i) + }; + by(true).or_else(|| by(false)) + } +} + +/// A value a control takes in a change. +#[derive(Clone, Debug, PartialEq)] +pub enum UiValue { + Text(String), + Number(f64), + Index(Option), +} + +/// What the person did with a dialog. +#[derive(Clone, Debug, PartialEq)] +pub enum UiEvent { + /// A click on a button, check box or radio button. + Click(usize), + /// A new value for an edit field, a slider or a list. + Change(usize, UiValue), + /// The dialog's close box. + Close, +} + +impl UiEvent { + /// The event as `show()` takes it. + pub(crate) fn data(&self) -> Data { + let event = |e: &str| ("event".to_string(), Data::String(e.into())); + let id = |i: usize| ("id".to_string(), Data::Number(i as f64)); + match self { + Self::Click(i) => Data::Object(vec![event("click"), id(*i)]), + Self::Change(i, v) => { + let value = match v { + UiValue::Text(t) => Data::String(t.clone()), + UiValue::Number(n) => Data::Number(*n), + UiValue::Index(Some(k)) => Data::Number(*k as f64), + UiValue::Index(None) => Data::Null, + }; + Data::Object(vec![event("change"), id(*i), ("value".into(), value)]) + } + Self::Close => Data::Object(vec![event("close")]), + } + } +} + +/// Checks `event` against `dialog`. → the event as the dialog takes it: a slider's value clamped +/// to its range. +pub fn check_event(dialog: &ScriptUiDialog, event: UiEvent) -> Result { + let id = match &event { + UiEvent::Close => return Ok(event), + UiEvent::Click(i) | UiEvent::Change(i, _) => *i, + }; + let Some(n) = dialog.nodes.get(id).filter(|_| id > 0) else { return Err(format!("the dialog has no control {id}")) }; + if !n.enabled || !n.visible { + return Err(format!("the control {} is disabled or hidden", label(n))); + } + match event { + UiEvent::Click(_) if n.kind.clicks() => Ok(event), + UiEvent::Click(_) => Err(format!("the control {} cannot be clicked", label(n))), + UiEvent::Change(_, UiValue::Text(t)) if n.kind == UiKind::EditText && !n.readonly => { + if t.len() > MAX_TEXT_BYTES { + return Err("the text is longer than 16 KiB".into()); + } + Ok(UiEvent::Change(id, UiValue::Text(t))) + } + UiEvent::Change(_, UiValue::Number(v)) if n.kind == UiKind::Slider && v.is_finite() => { + Ok(UiEvent::Change(id, UiValue::Number(v.clamp(n.min, n.max)))) + } + UiEvent::Change(_, UiValue::Index(k)) if matches!(n.kind, UiKind::DropDownList | UiKind::ListBox) => match k { + Some(k) if k >= n.items.len() => Err(format!("the list {} has no item {k}", label(n))), + k => Ok(UiEvent::Change(id, UiValue::Index(k))), + }, + UiEvent::Change(..) => Err(format!("the control {} cannot take that change", label(n))), + UiEvent::Close => Ok(UiEvent::Close), + } +} + +fn label(n: &UiNode) -> String { + let shown = if n.name.is_empty() { &n.text } else { &n.name }; + super::dialogs::cut_to(shown, 64).to_string() +} + +/// A step of a `window` answer in `script.run`'s `answers`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UiStep { + /// The control's name or text; none for a close. + pub control: Option, + pub event: String, + pub value: Option, +} + +/// The steps of a `window` answer: `[{control, event: "click"} | {control, event: "change", value} +/// | {event: "close"}]`, where `control` is a string of at most 16 KiB and `value` a string, a +/// number or null. +pub(crate) fn parse_steps(v: &Value) -> Result, String> { + let Some(list) = v.as_array() else { return Err("is a window's answer, whose `value` must be a list of steps".into()) }; + list.iter().enumerate().map(|(i, s)| step(s).ok_or_else(|| format!("has a step {i} that is not a valid click, change or close"))).collect() +} + +fn step(s: &Value) -> Option { + let o = s.as_object()?; + if o.keys().any(|k| !matches!(k.as_str(), "control" | "event" | "value")) { + return None; + } + let control = match o.get("control") { + None => None, + Some(Value::String(c)) if c.len() <= MAX_TEXT_BYTES => Some(c.clone()), + Some(_) => return None, + }; + let value = o.get("value").cloned(); + let event = o.get("event").and_then(Value::as_str)?; + let fits = match event { + "close" => control.is_none() && value.is_none(), + "click" => control.is_some() && value.is_none(), + "change" => control.is_some() && matches!(value, Some(Value::String(_) | Value::Number(_) | Value::Null)), + _ => false, + }; + fits.then(|| UiStep { control, event: event.to_string(), value }) +} + +/// The event `step` is for `dialog`. +pub(crate) fn step_event(dialog: &ScriptUiDialog, step: &UiStep) -> Result { + let Some(control) = &step.control else { return Ok(UiEvent::Close) }; + let Some(id) = dialog.find(control) else { return Err(format!("the dialog has no control named {}", super::dialogs::cut_to(control, 64))) }; + let event = match (step.event.as_str(), &step.value) { + ("click", _) => UiEvent::Click(id), + (_, Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())), + (_, Some(Value::Number(n))) if matches!(dialog.nodes[id].kind, UiKind::DropDownList | UiKind::ListBox) => match n.as_u64() { + Some(k) => UiEvent::Change(id, UiValue::Index(Some(usize::try_from(k).unwrap_or(usize::MAX)))), + None => return Err("a list's `value` must be an item index or null".into()), + }, + (_, Some(Value::Number(n))) => UiEvent::Change(id, UiValue::Number(n.as_f64().unwrap_or(f64::NAN))), + (_, Some(Value::Null)) => UiEvent::Change(id, UiValue::Index(None)), + _ => return Err("a change's `value` must be a string, a number or null".into()), + }; + check_event(dialog, event) +} + +fn field<'a>(fields: &'a [(String, Data)], name: &str) -> &'a Data { + fields.iter().find(|(k, _)| k == name).map_or(&Data::Undefined, |(_, v)| v) +} + +fn bad(what: &str) -> HostError { + HostError::Type(format!("show: the dialog's description {what}")) +} + +/// A finite number. +fn number(d: &Data) -> Option { + match d { + Data::Number(n) if n.is_finite() => Some(*n), + _ => None, + } +} + +fn text(d: &Data, what: &str) -> Result { + match d { + Data::String(s) if s.len() <= MAX_TEXT_BYTES => Ok(s.clone()), + Data::String(_) => Err(HostError::Range(format!("show: {what} is longer than 16 KiB"))), + _ => Err(bad(&format!("has no {what}"))), + } +} + +fn extent(n: f64) -> f32 { + (n as f32).clamp(-MAX_EXTENT, MAX_EXTENT) +} + +fn align_name(s: &str, horizontal: Option) -> Result<(Option, Option), HostError> { + let a = match (s, horizontal) { + ("left", Some(true) | None) => (Some(Align::Start), None), + ("right", Some(true) | None) => (Some(Align::End), None), + ("top", Some(false) | None) => (None, Some(Align::Start)), + ("bottom", Some(false) | None) => (None, Some(Align::End)), + ("center", _) => (Some(Align::Center), Some(Align::Center)), + ("fill", _) => (Some(Align::Fill), Some(Align::Fill)), + _ => return Err(HostError::Error(format!("show: there is no alignment {}", super::dialogs::cut_to(s, 64)))), + }; + Ok(match horizontal { + Some(true) => (a.0, None), + Some(false) => (None, a.1), + None => a, + }) +} + +fn alignment(d: &Data) -> Result<(Option, Option), HostError> { + match d { + Data::Null | Data::Undefined => Ok((None, None)), + Data::String(s) => align_name(s, None), + Data::Array(a) if a.len() == 2 => { + let part = |d: &Data, h: bool| match d { + Data::String(s) => align_name(s, Some(h)), + _ => Err(bad("has an alignment that is not a name")), + }; + Ok((part(&a[0], true)?.0, part(&a[1], false)?.1)) + } + _ => Err(bad("has an alignment that is not a name or a pair of names")), + } +} + +fn numbers(d: &Data) -> Result, HostError> { + match d { + Data::Null | Data::Undefined => Ok(None), + Data::Array(a) if a.len() == N => { + let mut out = [0.0; N]; + for (o, v) in out.iter_mut().zip(a) { + *o = number(v).ok_or_else(|| bad("has a size that is not a number"))?; + } + Ok(Some(out)) + } + _ => Err(bad("has a size with the wrong count of numbers")), + } +} + +/// Reads, checks and lays out a dialog's description. +pub fn parse(d: &Data) -> Result { + let Data::Object(top) = d else { return Err(bad("is not an object")) }; + let Data::Array(list) = field(top, "nodes") else { return Err(bad("has no list of controls")) }; + if list.is_empty() { + return Err(bad("has no dialog")); + } + if list.len() > MAX_CONTROLS + 1 { + return Err(HostError::Range(format!("show: a dialog can hold at most {MAX_CONTROLS} controls"))); + } + let mut nodes: Vec = Vec::with_capacity(list.len()); + let mut depth: Vec = Vec::with_capacity(list.len()); + let mut items_total = 0usize; + for (i, n) in list.iter().enumerate() { + let Data::Object(f) = n else { return Err(bad("has a control that is not an object")) }; + let kind = match field(f, "kind") { + Data::String(k) => UiKind::parse(k).ok_or_else(|| bad("has a control of a kind that does not exist"))?, + _ => return Err(bad("has a control without a kind")), + }; + let parent = number(field(f, "parent")).ok_or_else(|| bad("has a control without its container"))?; + let parent = if i == 0 { + if kind != UiKind::Dialog || parent != -1.0 { + return Err(bad("does not start with the dialog")); + } + 0 + } else { + let p = parent as usize; + if parent < 0.0 || parent.fract() != 0.0 || p >= i || kind == UiKind::Dialog { + return Err(bad("has a control before its container")); + } + if !nodes[p].kind.container() { + return Err(bad("has a control inside a control that holds none")); + } + p + }; + let level = if i == 0 { 0 } else { depth[parent] + 1 }; + if level > MAX_DEPTH { + return Err(HostError::Range(format!("show: controls can be nested at most {MAX_DEPTH} deep"))); + } + depth.push(level); + let flag = |name: &str| matches!(field(f, name), Data::Bool(true)); + let (parent_enabled, parent_visible) = if i == 0 { (true, true) } else { (nodes[parent].enabled, nodes[parent].visible) }; + let items = match field(f, "items") { + Data::Array(a) => a.iter().map(|t| text(t, "a list item's text")).collect::, _>>()?, + _ => Vec::new(), + }; + items_total = items_total.saturating_add(items.len()); + if items_total > MAX_ITEMS { + return Err(HostError::Range(format!("show: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + let selection = number(field(f, "selection")).map(|k| k as usize).filter(|k| *k < items.len()); + let (min, max) = (number(field(f, "minvalue")).unwrap_or(0.0), number(field(f, "maxvalue")).unwrap_or(100.0)); + if min > max { + return Err(HostError::Range("show: a slider's or progress bar's minvalue is larger than its maxvalue".into())); + } + let orientation = match field(f, "orientation") { + Data::String(s) if s == "row" => Orientation::Row, + Data::String(s) if s == "column" => Orientation::Column, + Data::String(s) if s == "stack" => Orientation::Stack, + Data::Undefined => Orientation::Column, + _ => return Err(HostError::Error("show: a container's orientation must be row, column or stack".into())), + }; + let bounds = numbers::<4>(field(f, "bounds"))?.map(|[l, t, r, b]| { + let (l, t) = (extent(l), extent(t)); + UiRect { x: l, y: t, w: (extent(r) - l).clamp(0.0, MAX_EXTENT), h: (extent(b) - t).clamp(0.0, MAX_EXTENT) } + }); + let size = numbers::<2>(field(f, "size"))?.map_or([None, None], |[w, h]| [(w > 0.0).then(|| extent(w)), (h > 0.0).then(|| extent(h))]); + let margins = numbers::<4>(field(f, "margins"))?.map_or([0.0; 4], |m| m.map(|v| extent(v).max(0.0))); + nodes.push(UiNode { + kind, + parent, + name: text(field(f, "name"), "a control's name")?, + text: text(field(f, "text"), "a control's text")?, + enabled: flag("enabled") && parent_enabled, + visible: flag("visible") && parent_visible, + checked: flag("value"), + value: number(field(f, "value")).unwrap_or(0.0).clamp(min, max), + min, + max, + items, + selection, + multiline: flag("multiline"), + readonly: flag("readonly"), + rect: UiRect::default(), + orientation, + align_children: alignment(field(f, "alignChildren"))?, + alignment: alignment(field(f, "alignment"))?, + spacing: number(field(f, "spacing")).map_or(0.0, |s| extent(s).max(0.0)), + margins, + size, + bounds, + }); + } + let target = |name: &str| number(field(top, name)).map(|k| k as usize).filter(|k| nodes.get(*k).is_some_and(|n| n.kind == UiKind::Button)); + let (default_element, cancel_element) = (target("defaultElement"), target("cancelElement")); + let mut dialog = ScriptUiDialog { nodes, default_element, cancel_element, shown: 0 }; + layout(&mut dialog); + Ok(dialog) +} + +/// A control's own size, by VectorCraft's estimates. +fn own_size(n: &UiNode) -> [f32; 2] { + let chars = |s: &str| s.chars().count() as f32; + let widest = |lines: &mut dyn Iterator| lines.map(chars).fold(0.0, f32::max); + let lines = |s: &str| s.lines().count().max(1) as f32; + let longest_item = n.items.iter().map(|t| chars(t)).fold(0.0, f32::max); + match n.kind { + UiKind::StaticText => [widest(&mut n.text.lines()) * CHAR + 4.0, lines(&n.text) * LINE + 4.0], + UiKind::Button => [(chars(&n.text) * CHAR + 24.0).max(80.0), 24.0], + UiKind::CheckBox | UiKind::RadioButton => [chars(&n.text) * CHAR + 24.0, 20.0], + UiKind::EditText if n.multiline => [(widest(&mut n.text.lines()) * CHAR + 12.0).max(160.0), lines(&n.text).max(3.0) * LINE + 10.0], + UiKind::EditText => [(chars(&n.text) * CHAR + 12.0).max(80.0), 24.0], + UiKind::DropDownList => [(longest_item * CHAR + 40.0).max(100.0), 24.0], + UiKind::ListBox => [(longest_item * CHAR + 24.0).max(120.0), (n.items.len() as f32).clamp(3.0, 10.0) * 18.0 + 6.0], + UiKind::Slider => [160.0, 20.0], + UiKind::ProgressBar => [160.0, 12.0], + UiKind::Dialog | UiKind::Group | UiKind::Panel => [0.0, 0.0], + } +} + +/// Lays the dialog out: each control's size from the last to the first, then each place from the +/// first to the last. +fn layout(d: &mut ScriptUiDialog) { + let n = d.nodes.len(); + let mut kids: Vec> = vec![Vec::new(); n]; + for (i, node) in d.nodes.iter().enumerate().skip(1) { + kids[node.parent].push(i); + } + let mut size = vec![[0.0f32; 2]; n]; + for i in (0..n).rev() { + let node = &d.nodes[i]; + let mut s = if node.kind.container() { + let [l, t, r, b] = node.margins; + let (mut main, mut cross, mut count, mut reach) = (0.0f32, 0.0f32, 0usize, [0.0f32; 2]); + for &k in &kids[i] { + if let Some(bounds) = d.nodes[k].bounds { + reach = [reach[0].max(bounds.x + bounds.w), reach[1].max(bounds.y + bounds.h)]; + continue; + } + let [w, h] = size[k]; + count += 1; + match node.orientation { + Orientation::Row => (main, cross) = (main + w, cross.max(h)), + Orientation::Column => (main, cross) = (main + h, cross.max(w)), + Orientation::Stack => (main, cross) = (main.max(w), cross.max(h)), + } + } + if node.orientation != Orientation::Stack { + main += node.spacing * count.saturating_sub(1) as f32; + } + let (w, h) = match node.orientation { + Orientation::Row | Orientation::Stack => (main, cross), + Orientation::Column => (cross, main), + }; + [(w + l + r).max(reach[0]), (h + t + b).max(reach[1])] + } else { + own_size(node) + }; + for axis in 0..2 { + if let Some(v) = node.size[axis] { + s[axis] = v; + } + } + if let Some(b) = node.bounds { + s = [b.w, b.h]; + } + size[i] = [s[0].clamp(0.0, MAX_EXTENT), s[1].clamp(0.0, MAX_EXTENT)]; + } + d.nodes[0].rect = UiRect { x: 0.0, y: 0.0, w: size[0][0], h: size[0][1] }; + for i in 0..n { + if !d.nodes[i].kind.container() { + continue; + } + let node = d.nodes[i].clone(); + let [l, t, r, b] = node.margins; + let (x, y) = (node.rect.x + l, node.rect.y + t); + let (cw, ch) = ((node.rect.w - l - r).max(0.0), (node.rect.h - t - b).max(0.0)); + let mut cursor = 0.0f32; + for &k in &kids[i] { + let kid = &d.nodes[k]; + let rect = if let Some(bounds) = kid.bounds { + UiRect { x: node.rect.x + bounds.x, y: node.rect.y + bounds.y, w: bounds.w, h: bounds.h } + } else { + let [w, h] = size[k]; + let h_align = kid.alignment.0.or(node.align_children.0).unwrap_or(Align::Center); + let v_align = kid.alignment.1.or(node.align_children.1).unwrap_or(Align::Center); + let place = |align: Align, own: f32, room: f32| match align { + Align::Start => (0.0, own), + Align::End => ((room - own).max(0.0), own), + Align::Center => (((room - own) / 2.0).max(0.0), own), + Align::Fill => (0.0, room.max(own)), + }; + match node.orientation { + Orientation::Row => { + let (dy, kh) = place(v_align, h, ch); + let r = UiRect { x: x + cursor, y: y + dy, w, h: kh }; + cursor += w + node.spacing; + r + } + Orientation::Column => { + let (dx, kw) = place(h_align, w, cw); + let r = UiRect { x: x + dx, y: y + cursor, w: kw, h }; + cursor += h + node.spacing; + r + } + Orientation::Stack => { + let (dx, kw) = place(h_align, w, cw); + let (dy, kh) = place(v_align, h, ch); + UiRect { x: x + dx, y: y + dy, w: kw, h: kh } + } + } + }; + d.nodes[k].rect = UiRect { + x: rect.x.clamp(-MAX_EXTENT, MAX_EXTENT), + y: rect.y.clamp(-MAX_EXTENT, MAX_EXTENT), + w: rect.w.clamp(0.0, MAX_EXTENT), + h: rect.h.clamp(0.0, MAX_EXTENT), + }; + } + } +} + +/// The dialog of one `show()`: the steps left for a run with nobody to ask, and how many events it +/// took. +pub(crate) struct Showing { + pub(crate) dialog: ScriptUiDialog, + pub(crate) steps: Option>, + pub(crate) events: u64, +} + +impl Showing { + /// The report's record of the dialog, with its `answer`: the result of `show()`, `"stop"`, + /// `"missing"` or `"error"`. + pub(crate) fn record(&self, answer: Value) -> Value { + let mut r = Map::new(); + r.insert("kind".into(), json!("window")); + r.insert("title".into(), json!(super::dialogs::cut_to(self.dialog.title(), super::dialogs::MAX_TITLE_BYTES))); + r.insert("controls".into(), json!(self.dialog.nodes.len().saturating_sub(1))); + r.insert("events".into(), json!(self.events)); + r.insert("answer".into(), answer); + Value::Object(r) + } +} + +/// The host function `name` of `Window`, for the run `link` holds. +fn function(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> HostItem { + let l = link.clone(); + HostItem::Function(Rc::new(move |a| f(&*super::current(&l)?, &a))) +} + +/// Adds `Window` to the realm, for the run `link` holds. +pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> { + realm.define_script_ui(vec![("open".into(), function(link, open)), ("wait".into(), function(link, wait)), ("end".into(), function(link, end))]) +} + +fn described(host: &Host, args: &[Data]) -> Result { + host.charge_call(args.iter().map(super::data_size).sum())?; + parse(args.first().unwrap_or(&Data::Undefined)) +} + +fn open(host: &Host, args: &[Data]) -> Result { + let dialog = described(host, args)?; + host.dialogs.window_open(dialog)?; + Ok(Data::Undefined) +} + +fn wait(host: &Host, args: &[Data]) -> Result { + let dialog = described(host, args)?; + host.dialogs.window_wait(dialog) +} + +fn end(host: &Host, args: &[Data]) -> Result { + let result = number(args.first().unwrap_or(&Data::Undefined)).unwrap_or(0.0); + let normal = matches!(args.get(1), Some(Data::Bool(true))); + host.dialogs.window_end(result, normal)?; + Ok(Data::Undefined) +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e524d1c63c..58addcd9fe 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -177,6 +177,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_scriptui; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_scriptui.rs b/crates/engine/src/tests/script_scriptui.rs new file mode 100644 index 0000000000..24a6052154 --- /dev/null +++ b/crates/engine/src/tests/script_scriptui.rs @@ -0,0 +1,365 @@ +//! ScriptUI dialogs in a script: the description the engine checks and lays out, the `window` +//! answers a run with nobody to ask takes from `answers`, the wait in the app, Stop, and the +//! report's `dialogs`. + +use serde_json::{Value, json}; +use vectorcraft_js::{Data, HostError}; + +use crate::script::scriptui::{self, MAX_CONTROLS, MAX_DEPTH, MAX_EXTENT, MAX_TEXT_BYTES}; +use crate::script::{ScriptUiDialog, UiEvent, UiKind, UiValue}; +use crate::*; + +/// One open document with one rectangle. +fn one_doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s +} + +fn art(s: &Session) -> (String, usize) { + let d = &s.documents()[0]; + (format!("{:?}", d.doc.layers), d.history.undo.len()) +} + +fn headless(s: &mut Session, source: &str, answers: Value) -> Result { + s.execute("script.run", &json!({"source": source, "name": "w.js", "answers": answers})) +} + +/// A run in the app of `source`, one slice in. +fn framed(s: &mut Session, source: &str) { + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "w.js"})).unwrap()["running"], true); + assert!(s.script_pump().is_none()); +} + +/// Pumps the run in the app until it ends or waits at a ScriptUI dialog (`None`). +fn pump(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_window().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +fn window(steps: Value) -> Value { + json!([{"kind": "window", "value": steps}]) +} + +const EDIT: &str = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});"; + +/// A dialog with a field, a check box, a slider, a list and OK and Cancel. +const FORM: &str = "var w = new Window('dialog', 'Settings'); var g = w.add('group'); \ + g.add('statictext', undefined, 'Name:'); var name = g.add('edittext', undefined, 'first', {name: 'name'}); \ + var bold = w.add('checkbox', undefined, 'Bold'); var size = w.add('slider', undefined, 5, 0, 10); size.name = 'size'; \ + var pick = w.add('dropdownlist', undefined, ['a', 'b', 'c']); pick.name = 'pick'; \ + var ok = w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel');"; + +#[test] +fn a_run_with_nobody_to_ask_takes_the_steps_of_its_window_answer() { + let mut s = one_doc(); + let source = format!( + "{EDIT} {FORM} bold.onClick = function () {{ name.text = 'bolded'; }}; var r = w.show(); vc.log([r, name.text, bold.value, size.value, pick.selection.text]);" + ); + let steps = json!([ + {"control": "Bold", "event": "click"}, + {"control": "size", "event": "change", "value": 99}, + {"control": "pick", "event": "change", "value": 2}, + {"control": "OK", "event": "click"}, + ]); + let r = headless(&mut s, &source, window(steps)).unwrap(); + assert_eq!(r["log"], json!([[1, "bolded", true, 10, "c"]]), "the slider's value is clamped to its range: {r}"); + assert_eq!(r["dialogs"], json!([{"kind": "window", "title": "Settings", "controls": 8, "events": 4, "answer": 1}])); + let cancel = headless(&mut s, &format!("{FORM} vc.log(w.show());"), window(json!([{"control": "Cancel", "event": "click"}]))).unwrap(); + assert_eq!(cancel["log"], json!([2])); + let closed = headless(&mut s, &format!("{FORM} vc.log(w.show());"), window(json!([{"event": "close"}]))).unwrap(); + assert_eq!(closed["log"], json!([0])); +} + +#[test] +fn a_missing_wrong_or_unused_step_ends_the_run_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + let source = format!("{EDIT} {FORM} try {{ w.show(); }} catch (e) {{ vc.log('caught'); }}"); + for (given, says) in [ + (json!([]), "`answers` has no answer left for this dialog"), + (json!([{"kind": "alert", "value": "ok"}]), "is for alert, not window"), + (window(json!([])), "has no step left"), + (window(json!([{"control": "Nothing", "event": "click"}])), "the dialog has no control named Nothing"), + (window(json!([{"control": "Name:", "event": "click"}])), "cannot be clicked"), + (window(json!([{"control": "pick", "event": "change", "value": 3}])), "has no item 3"), + (window(json!([{"control": "OK", "event": "click"}, {"event": "close"}])), "has 1 step the dialog did not use"), + ] { + let e = headless(&mut s, &source, given.clone()).unwrap_err().to_string(); + assert!(e.contains(says), "{given}: {e}"); + assert_eq!(art(&s), before, "{given}"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!([]), "a missing answer cannot be caught: {report}"); + assert_eq!(report["dialogs"][0]["answer"], "missing", "{report}"); + } +} + +#[test] +fn window_answers_that_do_not_parse_are_refused_before_the_run() { + let mut s = one_doc(); + let bad = |i: usize| format!("`answers[0]` has a step {i} that is not a valid click, change or close"); + for (steps, says) in [ + (json!("click"), "`answers[0]` is a window's answer, whose `value` must be a list of steps".to_string()), + (json!([1]), bad(0)), + (json!([{"event": "close"}, {"event": "tap", "control": "OK"}]), bad(1)), + (json!([{"event": "click"}]), bad(0)), + (json!([{"event": "click", "control": "OK", "value": 1}]), bad(0)), + (json!([{"event": "change", "control": "x"}]), bad(0)), + (json!([{"event": "change", "control": "x", "value": [1]}]), bad(0)), + (json!([{"event": "change", "control": "x".repeat(MAX_TEXT_BYTES + 1), "value": 1}]), bad(0)), + (json!([{"event": "close", "control": "x"}]), bad(0)), + (json!([{"event": "close", "extra": 1}]), bad(0)), + ] { + let e = headless(&mut s, "1", window(steps.clone())).unwrap_err().to_string(); + assert!(e.contains(&says), "{steps}: {e}"); + } +} + +#[test] +fn a_framed_run_waits_at_show_and_runs_each_handler_with_the_persons_events() { + let mut s = one_doc(); + framed( + &mut s, + &format!("{EDIT} {FORM} bold.onClick = function () {{ size.enabled = !bold.value; }}; var r = w.show(); vc.log([r, name.text, size.value]);"), + ); + let d = s.script_window().expect("show waits"); + assert_eq!(d.title(), "Settings"); + assert_eq!(d.nodes.len(), 9); + assert_eq!((d.nodes[3].kind, d.nodes[3].text.as_str()), (UiKind::EditText, "first")); + let bold = d.find("Bold").unwrap(); + let size = d.find("size").unwrap(); + assert!(s.script_window_answer(UiEvent::Click(d.find("Name:").unwrap())).is_err(), "static text takes no click"); + assert!(s.script_window_answer(UiEvent::Change(3, UiValue::Text("x".repeat(MAX_TEXT_BYTES + 1)))).is_err()); + assert!(s.script_window_answer(UiEvent::Click(99)).is_err()); + s.script_window_answer(UiEvent::Click(bold)).unwrap(); + assert!(s.script_window_answer(UiEvent::Close).is_err(), "nothing waits until the run goes on"); + assert!(pump(&mut s).is_none()); + let d = s.script_window().unwrap(); + assert!(d.nodes[bold].checked); + assert!(!d.nodes[size].enabled, "the handler disabled the slider"); + assert!(s.script_window_answer(UiEvent::Change(size, UiValue::Number(3.0))).is_err(), "a disabled control takes no events"); + s.script_window_answer(UiEvent::Change(3, UiValue::Text("Ann".into()))).unwrap(); + assert!(pump(&mut s).is_none()); + s.script_window_answer(UiEvent::Click(d.default_element.unwrap())).unwrap(); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[1, "Ann", 5]])); + assert_eq!(r["dialogs"][0]["events"], 3); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script", "a finished run is one undo step"); +} + +#[test] +fn stop_while_show_waits_ends_the_run_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + framed(&mut s, &format!("{EDIT} {FORM} w.show(); vc.log('after');")); + assert!(s.script_window().is_some()); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert_eq!(s.script_window(), None, "a run asked to stop no longer waits"); + assert!(s.script_window_answer(UiEvent::Close).is_err()); + assert!(s.script_pump().unwrap().is_err()); + let report = s.script_report().unwrap(); + assert_eq!((report["kind"].as_str(), &report["log"]), (Some("stopped"), &json!([])), "{report}"); + assert_eq!(report["dialogs"][0]["answer"], "stop"); + assert_eq!(art(&s), before); + framed(&mut s, &format!("{EDIT} {FORM} w.show();")); + assert!(s.script_abandon(), "quitting while a dialog waits abandons the run"); + assert_eq!(art(&s), before); +} + +#[test] +fn a_handler_that_loops_ends_the_run_at_its_fuel_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + let source = format!("{EDIT} {FORM} bold.onClick = function () {{ for (;;) {{}} }}; w.show();"); + let e = headless(&mut s, &source, window(json!([{"control": "Bold", "event": "click"}]))).unwrap_err().to_string(); + assert!(e.contains("limit") || e.contains("fuel") || e.contains("instructions"), "{e}"); + assert_eq!(art(&s), before); + assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "error"); +} + +#[test] +fn a_show_in_a_callback_throws_in_the_app() { + let mut s = one_doc(); + s.script_frames = true; + let source = "var w = new Window('dialog'); w.add('button', undefined, 'OK'); var e = ''; try { [1].forEach(function () { w.show(); }); } catch (x) { e = x.message; } vc.log(e);"; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "w.js"})).unwrap()["running"], true); + let r = pump(&mut s).expect("show does not wait in a callback").unwrap(); + assert!(r["log"][0].as_str().unwrap().contains("cannot open inside a callback"), "{r}"); +} + +fn node(kind: &str, parent: f64) -> Data { + Data::Object(vec![ + ("kind".into(), Data::String(kind.into())), + ("parent".into(), Data::Number(parent)), + ("name".into(), Data::String(String::new())), + ("text".into(), Data::String("t".into())), + ("enabled".into(), Data::Bool(true)), + ("visible".into(), Data::Bool(true)), + ]) +} + +fn description(nodes: Vec) -> Data { + Data::Object(vec![ + ("nodes".into(), Data::Array(nodes)), + ("defaultElement".into(), Data::Number(-1.0)), + ("cancelElement".into(), Data::Number(-1.0)), + ]) +} + +fn with(n: Data, name: &str, value: Data) -> Data { + let Data::Object(mut fields) = n else { panic!("a node is an object") }; + fields.retain(|(k, _)| k != name); + fields.push((name.into(), value)); + Data::Object(fields) +} + +fn refused(d: &Data) -> String { + match scriptui::parse(d) { + Err(HostError::Type(m) | HostError::Range(m) | HostError::Error(m)) => m, + other => panic!("not refused: {other:?}"), + } +} + +#[test] +fn a_description_out_of_order_too_large_too_deep_or_too_long_is_refused() { + let dialog = node("dialog", -1.0); + assert!(refused(&description(vec![])).contains("has no dialog")); + assert!(refused(&description(vec![node("group", -1.0)])).contains("does not start with the dialog")); + assert!(refused(&description(vec![dialog.clone(), node("button", 2.0), node("group", 0.0)])).contains("before its container")); + assert!(refused(&description(vec![dialog.clone(), node("button", 1.0)])).contains("before its container"), "a control cannot hold itself"); + assert!(refused(&description(vec![dialog.clone(), node("button", 0.0), node("button", 1.0)])).contains("holds none")); + assert!(refused(&description(vec![dialog.clone(), node("dialog", 0.0)])).contains("before its container")); + let many: Vec = std::iter::once(dialog.clone()).chain((0..=MAX_CONTROLS).map(|_| node("button", 0.0))).collect(); + assert!(refused(&description(many)).contains(&format!("at most {MAX_CONTROLS} controls"))); + let deep: Vec = std::iter::once(dialog.clone()).chain((0..=MAX_DEPTH).map(|k| node("group", k as f64))).collect(); + assert!(refused(&description(deep)).contains(&format!("at most {MAX_DEPTH} deep"))); + let long = with(node("statictext", 0.0), "text", Data::String("x".repeat(MAX_TEXT_BYTES + 1))); + assert!(refused(&description(vec![dialog.clone(), long])).contains("longer than 16 KiB")); + let slider = with(with(node("slider", 0.0), "minvalue", Data::Number(5.0)), "maxvalue", Data::Number(1.0)); + assert!(refused(&description(vec![dialog.clone(), slider])).contains("minvalue is larger")); + let nan = with(node("button", 0.0), "bounds", Data::Array(vec![Data::Number(0.0), Data::Number(f64::NAN), Data::Number(1.0), Data::Number(1.0)])); + assert!(refused(&description(vec![dialog.clone(), nan])).contains("not a number")); + let orient = with(dialog.clone(), "orientation", Data::String("diagonal".into())); + assert!(refused(&description(vec![orient])).contains("row, column or stack")); + let align = with(node("button", 0.0), "alignment", Data::String("sideways".into())); + assert!(refused(&description(vec![dialog, align])).contains("no alignment sideways")); +} + +#[test] +fn sizes_and_places_are_clamped_and_the_layout_follows_the_containers() { + let dialog = with(with(node("dialog", -1.0), "orientation", Data::String("column".into())), "margins", Data::Array(vec![Data::Number(10.0); 4])); + let row = with(with(node("group", 0.0), "orientation", Data::String("row".into())), "spacing", Data::Number(5.0)); + let a = with(node("button", 1.0), "size", Data::Array(vec![Data::Number(100.0), Data::Number(20.0)])); + let b = with(node("button", 1.0), "size", Data::Array(vec![Data::Number(50.0), Data::Number(30.0)])); + let huge = + with(node("statictext", 0.0), "bounds", Data::Array(vec![Data::Number(-1e12), Data::Number(0.0), Data::Number(1e12), Data::Number(1e300)])); + let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog, row, a, b, huge])).unwrap(); + assert_eq!((d.nodes[1].rect.w, d.nodes[1].rect.h), (155.0, 30.0), "a row adds widths and spacing, and takes the tallest height"); + assert_eq!((d.nodes[2].rect.x, d.nodes[3].rect.x), (10.0, 115.0)); + assert_eq!(d.nodes[2].rect.y, 15.0, "a shorter control is centered in its row"); + for n in &d.nodes { + for v in [n.rect.x, n.rect.y, n.rect.w, n.rect.h] { + assert!(v.is_finite() && v.abs() <= MAX_EXTENT, "{:?}", n.rect); + } + } + let (w, h) = d.size(); + assert!(w <= MAX_EXTENT && h <= MAX_EXTENT); +} + +/// A description of arbitrary kinds, containers in any order, numbers of any size (infinite and +/// not-a-number ones included) and texts of any length. +fn any_description() -> impl proptest::strategy::Strategy { + use proptest::prelude::*; + let kind = prop_oneof![ + Just("dialog"), + Just("group"), + Just("panel"), + Just("statictext"), + Just("edittext"), + Just("button"), + Just("checkbox"), + Just("radiobutton"), + Just("dropdownlist"), + Just("listbox"), + Just("slider"), + Just("progressbar"), + Just("wobble"), + ]; + let number = prop_oneof![1 => Just(f64::NAN), 1 => Just(f64::INFINITY), 1 => Just(-1e300), 1 => any::(), 6 => -50.0..400.0f64]; + let text = prop_oneof![2 => Just(String::new()), 8 => "[ -~]{0,40}", 1 => Just("x".repeat(MAX_TEXT_BYTES + 1))]; + let bounds = proptest::option::of(proptest::collection::vec(number.clone(), 4..=4)); + let size = proptest::option::of(proptest::collection::vec(number.clone(), 2..=2)); + // The container is a share of the controls before this one, or with a share past 1, one after it. + let fields = (kind, 0.0..1.1f64, text, bounds, size, 0..4usize, number); + proptest::collection::vec(fields, 0..40).prop_map(|nodes| { + let mut containers = vec![0usize]; + let mut out = Vec::new(); + for (i, (kind, share, text, bounds, size, items, value)) in nodes.into_iter().enumerate() { + let kind = if i == 0 { "dialog" } else { kind }; + let parent = match i { + 0 => -1.0, + _ if share >= 1.0 => (i + 1) as f64, + _ => containers[((share * containers.len() as f64) as usize).min(containers.len() - 1)] as f64, + }; + if matches!(kind, "group" | "panel") { + containers.push(i); + } + let numbers = |v: Option>| v.map_or(Data::Null, |v| Data::Array(v.into_iter().map(Data::Number).collect())); + let mut n = with(with(node(kind, parent), "text", Data::String(text)), "bounds", numbers(bounds)); + n = with(n, "size", numbers(size)); + n = with(n, "items", Data::Array((0..items).map(|k| Data::String(k.to_string())).collect())); + n = with(n, "selection", Data::Number(value)); + out.push(with(with(n, "minvalue", Data::Number(0.0)), "value", Data::Number(value))); + } + description(out) + }) +} + +proptest::proptest! { + #![proptest_config(proptest::prelude::ProptestConfig::with_cases(256))] + + /// Any description is refused with an error or laid out with every place and size finite and + /// within the limit. + #[test] + fn any_description_is_refused_or_laid_out_within_its_limits(d in any_description()) { + if let Ok(dialog) = scriptui::parse(&d) { + for n in &dialog.nodes { + for v in [n.rect.x, n.rect.y, n.rect.w, n.rect.h] { + proptest::prop_assert!(v.is_finite() && v.abs() <= MAX_EXTENT, "{:?}", n.rect); + } + proptest::prop_assert!(n.value.is_finite() && n.selection.is_none_or(|k| k < n.items.len())); + } + } + } +} + +#[test] +fn an_event_is_checked_against_the_dialog() { + let d = scriptui::parse(&description(vec![ + node("dialog", -1.0), + node("button", 0.0), + with(node("edittext", 0.0), "readonly", Data::Bool(true)), + with(with(with(node("slider", 0.0), "minvalue", Data::Number(0.0)), "maxvalue", Data::Number(10.0)), "value", Data::Number(4.0)), + with(node("listbox", 0.0), "items", Data::Array(vec![Data::String("a".into())])), + with(node("button", 0.0), "visible", Data::Bool(false)), + ])) + .unwrap(); + assert_eq!(scriptui::check_event(&d, UiEvent::Click(1)), Ok(UiEvent::Click(1))); + assert!(scriptui::check_event(&d, UiEvent::Click(0)).is_err(), "the dialog itself is no control"); + assert!(scriptui::check_event(&d, UiEvent::Change(2, UiValue::Text("x".into()))).is_err(), "a read-only field takes no text"); + assert_eq!(scriptui::check_event(&d, UiEvent::Change(3, UiValue::Number(-5.0))), Ok(UiEvent::Change(3, UiValue::Number(0.0)))); + assert!(scriptui::check_event(&d, UiEvent::Change(3, UiValue::Number(f64::NAN))).is_err()); + assert!(scriptui::check_event(&d, UiEvent::Change(4, UiValue::Index(Some(1)))).is_err()); + assert_eq!(scriptui::check_event(&d, UiEvent::Change(4, UiValue::Index(None))), Ok(UiEvent::Change(4, UiValue::Index(None)))); + assert!(scriptui::check_event(&d, UiEvent::Click(5)).is_err(), "a hidden control takes no events"); + assert_eq!(scriptui::check_event(&d, UiEvent::Close), Ok(UiEvent::Close)); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 660433b800..800b0f35df 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -40,10 +40,12 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ]; /// The names the host adds that stay inside the document and the run, by the object that has them. -/// Reading a file or a folder, a file dialog and a message to the person do not change anything -/// outside it. +/// Reading a file or a folder, a file dialog, a message to the person and a ScriptUI dialog do not +/// change anything outside it. const INSIDE: &[(&str, &str)] = &[ - ("", "$ File Folder alert confirm localize prompt toSource"), + ("", "$ File Folder Window alert confirm localize prompt toSource"), + ("Window.", "length prototype"), + ("Window.prototype.", "add center close constructor findElement hide show"), ("Object.prototype.", "toSource"), ("localize.", "length"), ("toSource.", "length"), diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 30de04cf12..f999a59b33 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -617,6 +617,7 @@ fn ask_pick(i: &mut Interp, kind: &'static str, me: Option<&Value>, prompt: &Val args: vec![Value::str(kind), prompt, Value::Bool(multi), start, types], keep: vec![Value::Bool(kind == "folder"), me.cloned().unwrap_or(Value::Null), filter.clone()], resume: picked, + failed: None, }) } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24c33d2fc5..bd78fa419d 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -193,18 +193,25 @@ pub(crate) type CodeObserver = Rc; pub(crate) type PausableFn = fn(&mut Interp, Value, &[Value]) -> JsResult; /// What a [`PausableFn`] does with the host's answer: it is given the values it kept and the -/// answer, and gives the result of its call. +/// answer, and gives the result of its call. One that puts another [`Pause`] in +/// [`Interp::again`] makes that host call next, and the call's result is what that pause's +/// resume function gives. pub(crate) type ResumeFn = fn(&mut Interp, &[Value], Value) -> JsResult; +/// What a [`Pause`] does with its kept values when its host call fails. +pub(crate) type FailFn = fn(&mut Interp, &[Value]); + /// The host call a [`PausableFn`] makes: the host function `host` with `args`. Its answer goes to /// `resume` with `keep`, at once when the host answers at once. When the host waits /// ([`crate::HostError::Wait`]), the run pauses at the call, and `resume` runs when the run goes on /// after [`crate::Realm::answer`]; a run ended while it waits ([`crate::Realm::end`]) drops it. +/// When the host call fails, `failed` is given `keep` before the error is thrown at the call. pub(crate) struct Pause { pub(crate) host: Value, pub(crate) args: Vec, pub(crate) keep: Vec, pub(crate) resume: ResumeFn, + pub(crate) failed: Option, } /// A [`Pause`] whose host call waits for its answer. @@ -276,6 +283,10 @@ pub(crate) struct Interp { /// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before /// the next instruction runs. pub(crate) resuming: Option, + /// The next host call a resume function asks for ([`ResumeFn`]). + pub(crate) again: Option, + /// ScriptUI's `Window` and its controls, when the host added them. + pub(crate) script_ui: Option, /// The message of the uncatchable error a host function ended the run with. pub(crate) host_abort: Option, /// How much a value passed to or from a host function may carry. @@ -528,6 +539,8 @@ impl Interp { can_wait: Rc::default(), waiting: false, resuming: None, + again: None, + script_ui: None, host_abort: None, data_limits: crate::DataLimits::default(), source_tag: crate::realm::UNKNOWN_SOURCE, @@ -758,6 +771,7 @@ impl Interp { roots.values.extend(self.stack.iter()); roots.values.extend(self.temp_roots.iter()); roots.values.extend(self.resuming.iter().flat_map(|r| r.keep.iter())); + roots.values.extend(self.again.iter().flat_map(|p| p.keep.iter().chain(p.args.iter()).chain(std::iter::once(&p.host)))); roots.values.push(&self.last_thrown); roots.values.push(&self.last_error); roots.values.push(&self.passing); @@ -774,6 +788,7 @@ impl Interp { roots.objects.push(self.global); roots.objects.extend(self.intrinsics.all()); roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); + roots.objects.extend(self.script_ui.iter().flat_map(crate::scriptui::Classes::objects)); roots.envs.push(self.global_env); self.heap.collect(&roots); // The collection counts the live total again, so bytes already released are not in it. @@ -2487,35 +2502,60 @@ impl Interp { /// Makes the host call a [`PausableFn`] gave, whose answer goes to its resume function. A host /// function is called as the script's own code calls it, so it may wait; then the resume /// function is kept for the answer [`crate::Realm::answer`] gives, and the value that stands - /// in for that answer is the call's result for now. + /// in for that answer is the call's result for now. A resume function that asks [`Self::again`] + /// makes that call next, in this loop, so a built-in may ask any number of times. fn ask(&mut self, p: Pause) -> JsResult { - let Pause { host, args, keep, resume } = p; - let mark = self.temp_roots.len(); - self.temp_roots.push(host.clone()); - self.temp_roots.extend(args.iter().cloned()); - self.temp_roots.extend(keep.iter().cloned()); - let was_waiting = self.waiting; - let answer = match self.func_of(&host) { - Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read), - _ => self.call(&host, &Value::Undefined, &args), - }; - self.temp_roots.truncate(mark); - let answer = answer?; - let r = Resumption { resume, keep }; - if self.waiting && !was_waiting { - self.resuming = Some(r); - return Ok(answer); + let mut p = p; + loop { + let Pause { host, args, keep, resume, failed } = p; + let mark = self.temp_roots.len(); + self.temp_roots.push(host.clone()); + self.temp_roots.extend(args.iter().cloned()); + self.temp_roots.extend(keep.iter().cloned()); + let was_waiting = self.waiting; + let answer = match self.func_of(&host) { + Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read), + _ => self.call(&host, &Value::Undefined, &args), + }; + if answer.is_err() + && let Some(failed) = failed + { + failed(self, &keep); + } + self.temp_roots.truncate(mark); + let answer = answer?; + let r = Resumption { resume, keep }; + if self.waiting && !was_waiting { + self.resuming = Some(r); + return Ok(answer); + } + let v = self.resume_once(r, answer)?; + match self.again.take() { + Some(next) => p = next, + None => return Ok(v), + } } - self.resume(r, answer) } - /// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function. + /// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function, and + /// makes the host call it asks for next, if any. fn resume(&mut self, r: Resumption, answer: Value) -> JsResult { + let v = self.resume_once(r, answer)?; + match self.again.take() { + Some(next) => self.ask(next), + None => Ok(v), + } + } + + fn resume_once(&mut self, r: Resumption, answer: Value) -> JsResult { let mark = self.temp_roots.len(); self.temp_roots.push(answer.clone()); self.temp_roots.extend(r.keep.iter().cloned()); let v = (r.resume)(self, &r.keep, answer); self.temp_roots.truncate(mark); + if v.is_err() { + self.again = None; + } v } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1561d71dfe..c953004550 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -67,6 +67,7 @@ mod realm; mod regexp; mod regexp_builtins; mod regexp_vm; +pub mod scriptui; mod string_builtins; mod token; mod value; @@ -209,6 +210,8 @@ mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod scriptui_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod text_tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index ee2cd364f8..ad8d10acce 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -256,6 +256,8 @@ impl Realm { interp.host_abort = None; interp.waiting = false; interp.resuming = None; + interp.again = None; + crate::scriptui::end_run(interp); interp.error_tag = UNKNOWN_SOURCE; interp.thrown_mark = None; interp.finally_marks.clear(); @@ -292,6 +294,8 @@ impl Realm { interp.join_stack.clear(); interp.waiting = false; interp.resuming = None; + interp.again = None; + crate::scriptui::end_run(interp); interp.passing = Value::Undefined; match result { Ok(v) => Ok(interp.to_js_value(&v)), @@ -488,6 +492,16 @@ impl Realm { } } + /// Adds ScriptUI's global constructor `Window` ([`crate::scriptui`]), whose dialogs the host + /// functions in `items` show: `open` and `wait`, each given the dialog's description, and + /// `end`, given the result of `show()` and whether `show()` ended normally. + pub fn define_script_ui(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> { + match crate::scriptui::install(&mut self.interp, items) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Adds the global constructors `File` and `Folder`, whose file system work the host functions /// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`, /// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`, diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs new file mode 100644 index 0000000000..9afc647960 --- /dev/null +++ b/crates/js/src/scriptui.rs @@ -0,0 +1,1026 @@ +//! ScriptUI's `Window` with modal dialogs, as the help page +//! describes it, whose +//! drawing a host does ([`crate::Realm::define_script_ui`]). +//! +//! `new Window("dialog"[, title, bounds, properties])` makes a dialog, with or without `new`. A +//! window of type `palette` or `window`, and a resource specification in place of the type, throw +//! an `Error` that says they are not available yet. `add(type[, bounds, text, properties])` adds a +//! control to a dialog, a `group` or a `panel` and returns it: `statictext`, `edittext`, `button`, +//! `checkbox`, `radiobutton`, `dropdownlist`, `listbox` (whose third argument is an array of item +//! texts), `slider` (third to fifth: value, minimum, maximum) and `progressbar` (value, maximum). +//! The other documented control types throw an `Error` that says they are not available yet. A +//! list's `add("item", text)` adds an item; its `selection` is an item or `null`, and takes an +//! item, an index or `null`. +//! +//! `show()` gives the host's `open` the dialog's description and runs `onShow`. Then, until the +//! dialog closes, it gives the host's `wait` the description again, and `wait` gives back what the +//! person did, which may pause the run ([`crate::interp::Pause`]): a `click` on a control, a +//! `change` with its new value, or a `close`. The control takes the change, its `onClick`, +//! `onChanging` or `onChange` runs, and the next description shows what the handler changed. A +//! button without `onClick` closes the dialog with 1 when it is the dialog's default element and +//! with 2 when it is its cancel element. `close(result)` closes the dialog after the running handler +//! returns, and `show()` gives `result`, or 0 without one; `onClose` runs first and keeps the dialog +//! open when it returns `false`. A dialog that is showing cannot be shown again, and no other dialog +//! can be shown while one is. When `show()` ends, the host's `end` is given its result and whether +//! it ended normally. +//! +//! An element keeps its kind, its container, its controls and a list's items in properties that a +//! script cannot change. The description lists the dialog first and every control after the +//! container that holds it; it is read with a loop, and a dialog with more than [`MAX_CONTROLS`] +//! controls, nested more than [`MAX_DEPTH`] deep, with more than [`MAX_ITEMS`] list items, or with a +//! text longer than [`MAX_TEXT_BYTES`] throws a `RangeError`. These are VectorCraft's own limits. + +use crate::HostItem; +use crate::builtins::{arg, constructor, method, native, pausable_method}; +use crate::heap::{Class, ENUMERABLE, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key}; +use crate::host::Data; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult, Pause}; +use crate::value::{Value, index_key}; + +/// The most controls a dialog holds, its groups and panels included. +pub const MAX_CONTROLS: usize = 512; +/// How deeply controls nest in a dialog: a control the dialog holds is at depth 1. +pub const MAX_DEPTH: usize = 16; +/// The most items a dialog's lists hold together. +pub const MAX_ITEMS: usize = 1024; +/// The most bytes (UTF-8) of one text in a dialog: a control's text or name, or a list item's. +pub const MAX_TEXT_BYTES: usize = 16 << 10; + +/// The control types `add` makes. +pub const BUILT: [&str; 11] = + ["group", "panel", "statictext", "edittext", "button", "checkbox", "radiobutton", "dropdownlist", "listbox", "slider", "progressbar"]; +/// The documented control types that are not available yet. +const LATER: [&str; 10] = + ["tabbedpanel", "tab", "scrollbar", "image", "iconbutton", "treeview", "flashplayer", "customview", "custombutton", "customboundedvalue"]; + +const KIND: &str = "__vcKind"; +const PARENT: &str = "__vcParent"; +const WINDOW: &str = "__vcWindow"; +const KIDS: &str = "__vcKids"; +const DEPTH: &str = "__vcDepth"; +const COUNT: &str = "__vcCount"; +const ITEM_COUNT: &str = "__vcItemCount"; +const CLOSING: &str = "__vcClosing"; +const ITEMS: &str = "__vcItems"; +const SELECTION: &str = "__vcSelection"; +const LIST: &str = "__vcList"; + +/// The objects of `Window`, kept by the realm, and the dialog that is showing. +#[derive(Clone, Debug)] +pub(crate) struct Classes { + window_proto: ObjId, + control_proto: ObjId, + item_proto: ObjId, + layout: ObjId, + host: ObjId, + selection_get: ObjId, + selection_set: ObjId, + showing: Option, +} + +impl Classes { + /// The objects a collection keeps. + pub(crate) fn objects(&self) -> Vec { + let mut all = vec![self.window_proto, self.control_proto, self.item_proto, self.layout, self.host, self.selection_get, self.selection_set]; + all.extend(self.showing); + all + } +} + +/// Forgets the dialog that was showing when a run ended where it was. +pub(crate) fn end_run(i: &mut Interp) { + if let Some(c) = i.script_ui.as_mut() { + c.showing = None; + } +} + +fn classes(i: &Interp) -> JsResult { + i.script_ui.clone().ok_or_else(|| Abrupt::Internal("Window is not installed".into())) +} + +fn error(i: &mut Interp, message: &str) -> Abrupt { + i.throw(ErrorType::Error, message) +} + +fn range(i: &mut Interp, message: &str) -> Abrupt { + i.throw(ErrorType::Range, message) +} + +/// The value of the own data property `name` of `o`, `undefined` when it has none. +fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { + Ok(match i.get_own_property(o, &key(name))? { + Some(Prop::Data { value, .. }) => value, + _ => Value::Undefined, + }) +} + +/// Sets the property `name` of `o` that a script can read but not change. +fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { + i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES))?; + i.define(o, key(name), Prop::Data { value, flags: 0 }) +} + +/// Sets the property `name` of `o` that a script can change. +fn set_open(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { + i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES))?; + i.define(o, key(name), Prop::Data { value, flags: OPEN }) +} + +fn number_slot(i: &Interp, o: ObjId, name: &str) -> JsResult { + Ok(match slot(i, o, name)? { + Value::Number(n) => n, + _ => 0.0, + }) +} + +fn object_slot(i: &Interp, o: ObjId, name: &str) -> JsResult> { + Ok(slot(i, o, name)?.as_object()) +} + +/// An element's kind, or `None` for a value that is not a ScriptUI window or control. +fn kind_of(i: &Interp, v: &Value) -> JsResult> { + let Some(o) = v.as_object() else { return Ok(None) }; + Ok(match slot(i, o, KIND)? { + Value::String(s) => Some((o, s.to_rust_string())), + _ => None, + }) +} + +/// `this` as an element, or a `TypeError` naming `what`. +fn element(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, String)> { + match kind_of(i, this)? { + Some(e) => Ok(e), + None => Err(i.type_error(&format!("{what}: this is not a ScriptUI window or control"))), + } +} + +/// Are `a` and `b` the same object? +fn same(a: &Value, b: &Value) -> bool { + matches!((a.as_object(), b.as_object()), (Some(x), Some(y)) if x == y) +} + +/// The values of an array made by [`list`]. +fn list_values(i: &Interp, a: ObjId) -> JsResult> { + let length = match &i.object(a)?.class { + Class::Array { length, .. } => *length, + _ => return Ok(Vec::new()), + }; + (0..length) + .map(|n| { + Ok(match i.get_own_property(a, &index_key(n))? { + Some(Prop::Data { value, .. }) => value, + _ => Value::Undefined, + }) + }) + .collect() +} + +/// A new array holding `items`: one a script cannot change unless `open`. +fn list(i: &mut Interp, items: &[Value], open: bool) -> JsResult { + i.rooted(items, |i| i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(items.len() + 1))))?; + let proto = i.intrinsics.array_proto; + let a = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: open }, Some(proto))); + let flags = if open { OPEN } else { ENUMERABLE }; + for (n, v) in items.iter().enumerate() { + let n = u32::try_from(n).map_err(|_| Abrupt::Internal("a list is too long".into()))?; + i.define(a, index_key(n), Prop::Data { value: v.clone(), flags })?; + } + i.object_mut(a)?.extensible = open; + Ok(a) +} + +/// Adds `v` to the end of the list in `o`'s slot `name`, and puts a copy a script can change in +/// its property `public`. +fn append(i: &mut Interp, o: ObjId, name: &str, public: &str, v: Value) -> JsResult<()> { + let mut items = match object_slot(i, o, name)? { + Some(a) => list_values(i, a)?, + None => Vec::new(), + }; + items.push(v); + i.rooted(&items.clone(), |i| { + let kept = list(i, &items, false)?; + set_slot(i, o, name, Value::Object(kept))?; + let copy = list(i, &items, true)?; + set_open(i, o, public, Value::Object(copy)) + }) +} + +fn text_arg(i: &mut Interp, v: &Value) -> JsResult { + Ok(match v { + Value::Undefined => Value::str(""), + v => Value::String(i.to_str(v)?), + }) +} + +/// A new element of `kind`, with the properties every element has. +fn new_element( + i: &mut Interp, + proto: ObjId, + kind: &str, + parent: Option, + window: Option, + depth: usize, + args: [&Value; 3], +) -> JsResult { + let [bounds, text, props] = args; + i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(32)))?; + let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + i.temp_roots.push(Value::Object(o)); + let window = window.unwrap_or(o); + let parent = parent.map_or(Value::Null, Value::Object); + let layout = classes(i)?.layout; + set_slot(i, o, KIND, Value::str(kind))?; + set_slot(i, o, PARENT, parent.clone())?; + set_slot(i, o, WINDOW, Value::Object(window))?; + set_slot(i, o, DEPTH, Value::Number(depth as f64))?; + set_open(i, o, "type", Value::str(kind))?; + set_open(i, o, "parent", parent)?; + set_open(i, o, "window", Value::Object(window))?; + let text = text_arg(i, text)?; + set_open(i, o, "text", text)?; + let props = match props { + Value::Object(_) => props.clone(), + _ => Value::Object(i.new_object()), + }; + set_open(i, o, "properties", props.clone())?; + let name = i.get_value(&props, &key("name"))?; + let name = text_arg(i, &name)?; + set_open(i, o, "name", name)?; + set_open(i, o, "enabled", Value::Bool(true))?; + set_open(i, o, "visible", Value::Bool(true))?; + if !matches!(bounds, Value::Undefined | Value::Null) { + set_open(i, o, "bounds", bounds.clone())?; + } + set_open(i, o, "layout", Value::Object(layout))?; + if matches!(kind, "dialog" | "group" | "panel") { + let kids = list(i, &[], false)?; + set_slot(i, o, KIDS, Value::Object(kids))?; + let children = list(i, &[], true)?; + set_open(i, o, "children", Value::Object(children))?; + set_open(i, o, "orientation", Value::str(if kind == "group" { "row" } else { "column" }))?; + set_open(i, o, "alignChildren", Value::str("center"))?; + set_open(i, o, "spacing", Value::Number(10.0))?; + set_open(i, o, "margins", Value::Number(if kind == "group" { 0.0 } else { 15.0 }))?; + } + Ok(o) +} + +/// `new Window(type[, title, bounds, properties])`. +fn window_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let kind = i.to_str(&arg(args, 0))?.to_rust_string(); + if kind.contains('{') { + return Err(error(i, "Window: resource specifications are not available yet; build the dialog with add()")); + } + let lower = kind.to_lowercase(); + if lower == "palette" || lower == "window" { + return Err(error(i, &format!("Window: a window of type {lower} is not available yet; use dialog"))); + } + if lower != "dialog" { + return Err(error(i, "Window: the type must be dialog, palette or window")); + } + let proto = classes(i)?.window_proto; + let mark = i.temp_roots.len(); + let r = (|| { + let o = new_element(i, proto, "dialog", None, None, 0, [&arg(args, 2), &arg(args, 1), &arg(args, 3)])?; + set_slot(i, o, COUNT, Value::Number(0.0))?; + set_slot(i, o, ITEM_COUNT, Value::Number(0.0))?; + Ok(Value::Object(o)) + })(); + i.temp_roots.truncate(mark); + r +} + +fn number_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let n = i.to_number(v)?; + if !n.is_finite() { + return Err(range(i, &format!("{what} is not a finite number"))); + } + Ok(n) +} + +/// `container.add(type[, bounds, text, properties])` and `list.add("item", text)`. +fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, kind) = element(i, &this, "add")?; + let ty = i.to_str(&arg(args, 0))?.to_rust_string(); + if kind == "dropdownlist" || kind == "listbox" { + if ty.to_lowercase() != "item" { + return Err(error(i, "add: a list holds only items")); + } + return add_item(i, o, &arg(args, 1)); + } + if !matches!(kind.as_str(), "dialog" | "group" | "panel") { + return Err(error(i, &format!("add: a {kind} holds no controls"))); + } + if ty.contains('{') { + return Err(error(i, "add: resource specifications are not available yet; add each control by its type")); + } + let ty = ty.to_lowercase(); + if LATER.contains(&ty.as_str()) { + return Err(error(i, &format!("add: the control type {ty} is not available yet"))); + } + let Some(&ty) = BUILT.iter().find(|b| **b == ty) else { return Err(error(i, &format!("add: there is no control type {ty}"))) }; + let depth = number_slot(i, o, DEPTH)? as usize + 1; + if depth > MAX_DEPTH { + return Err(range(i, &format!("add: controls can be nested at most {MAX_DEPTH} deep"))); + } + let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a control without its window".into())) }; + let count = number_slot(i, win, COUNT)?; + if count as usize >= MAX_CONTROLS { + return Err(range(i, &format!("add: a dialog can hold at most {MAX_CONTROLS} controls"))); + } + let props = arg(args, 3); + let list_kind = ty == "dropdownlist" || ty == "listbox"; + if ty == "listbox" && props.as_object().is_some() && i.get_value(&props, &key("multiselect"))?.truthy() { + return Err(error(i, "add: a list box that selects several items is not available yet")); + } + let proto = classes(i)?.control_proto; + let mark = i.temp_roots.len(); + let r = (|| { + let creation = if matches!(ty, "slider" | "progressbar") { Value::Undefined } else { props.clone() }; + let text = if list_kind || matches!(ty, "slider" | "progressbar") { Value::Undefined } else { arg(args, 2) }; + let c = new_element(i, proto, ty, Some(o), Some(win), depth, [&arg(args, 1), &text, &creation])?; + match ty { + "checkbox" | "radiobutton" => set_open(i, c, "value", Value::Bool(false))?, + "slider" | "progressbar" => { + let (value, min, max) = + if ty == "slider" { (arg(args, 2), arg(args, 3), arg(args, 4)) } else { (arg(args, 2), Value::Undefined, arg(args, 3)) }; + let given = |v: &Value| !matches!(v, Value::Undefined); + let value = if given(&value) { number_arg(i, &value, "add: the value")? } else { 0.0 }; + let min = if given(&min) { number_arg(i, &min, "add: the minimum value")? } else { 0.0 }; + let max = if given(&max) { number_arg(i, &max, "add: the maximum value")? } else { 100.0 }; + set_open(i, c, "minvalue", Value::Number(min))?; + set_open(i, c, "maxvalue", Value::Number(max))?; + set_open(i, c, "value", Value::Number(value))?; + } + "dropdownlist" | "listbox" => { + let kept = list(i, &[], false)?; + set_slot(i, c, ITEMS, Value::Object(kept))?; + set_slot(i, c, SELECTION, Value::Number(-1.0))?; + let items = list(i, &[], true)?; + set_open(i, c, "items", Value::Object(items))?; + let cl = classes(i)?; + i.define(c, key("selection"), Prop::Accessor { get: Some(cl.selection_get), set: Some(cl.selection_set), flags: ENUMERABLE })?; + } + _ => {} + } + if list_kind { + match arg(args, 2) { + Value::Undefined | Value::Null => {} + Value::Object(a) if matches!(i.object(a)?.class, Class::Array { .. }) => { + for item in list_values(i, a)? { + add_item(i, c, &item)?; + } + } + _ => return Err(i.type_error("add: give a list's items as an array")), + } + } + append(i, o, KIDS, "children", Value::Object(c))?; + set_slot(i, win, COUNT, Value::Number(count + 1.0))?; + Ok(Value::Object(c)) + })(); + i.temp_roots.truncate(mark); + r +} + +/// Adds an item with `text` to the list `o`. +fn add_item(i: &mut Interp, o: ObjId, text: &Value) -> JsResult { + let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a list without its window".into())) }; + let count = number_slot(i, win, ITEM_COUNT)?; + if count as usize >= MAX_ITEMS { + return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + let text = text_arg(i, text)?; + let proto = classes(i)?.item_proto; + i.rooted(std::slice::from_ref(&text), |i| { + i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(4)))?; + let item = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + i.rooted(&[Value::Object(item)], |i| { + set_slot(i, item, LIST, Value::Object(o))?; + set_open(i, item, "text", text.clone())?; + append(i, o, ITEMS, "items", Value::Object(item))?; + set_slot(i, win, ITEM_COUNT, Value::Number(count + 1.0))?; + Ok(Value::Object(item)) + }) + }) +} + +fn list_of(i: &mut Interp, this: &Value, what: &str) -> JsResult { + match kind_of(i, this)? { + Some((o, kind)) if kind == "dropdownlist" || kind == "listbox" => Ok(o), + _ => Err(i.type_error(&format!("{what}: this is not a list"))), + } +} + +fn items_of(i: &Interp, o: ObjId) -> JsResult> { + match object_slot(i, o, ITEMS)? { + Some(a) => list_values(i, a), + None => Ok(Vec::new()), + } +} + +fn selection_index(i: &Interp, o: ObjId) -> JsResult> { + let n = number_slot(i, o, SELECTION)?; + Ok((n >= 0.0).then_some(n as usize)) +} + +fn selection_get(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let o = list_of(i, &this, "selection")?; + let items = items_of(i, o)?; + Ok(selection_index(i, o)?.and_then(|n| items.get(n).cloned()).unwrap_or(Value::Null)) +} + +fn selection_set(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = list_of(i, &this, "selection")?; + let items = items_of(i, o)?; + let v = arg(args, 0); + let n = match &v { + Value::Undefined | Value::Null => -1.0, + Value::Number(n) if n.fract() == 0.0 && *n >= 0.0 && (*n as usize) < items.len() => *n, + Value::Number(n) => return Err(range(i, &format!("selection: the list has no item {n}"))), + v => match items.iter().position(|item| same(item, v)) { + Some(n) => n as f64, + None => return Err(i.type_error("selection: give an item of this list, its index or null")), + }, + }; + set_slot(i, o, SELECTION, Value::Number(n))?; + Ok(Value::Undefined) +} + +/// The list an item belongs to and its index there. +fn item_place(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, Option)> { + let list = match this.as_object() { + Some(o) => object_slot(i, o, LIST)?, + None => None, + }; + let Some(list) = list else { return Err(i.type_error(&format!("{what}: this is not a list item"))) }; + let index = items_of(i, list)?.iter().position(|item| same(item, this)); + Ok((list, index)) +} + +fn item_index(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (_, index) = item_place(i, &this, "index")?; + Ok(Value::Number(index.map_or(-1.0, |n| n as f64))) +} + +fn item_selected_get(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (list, index) = item_place(i, &this, "selected")?; + Ok(Value::Bool(index.is_some() && selection_index(i, list)? == index)) +} + +fn item_selected_set(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (list, index) = item_place(i, &this, "selected")?; + let Some(index) = index else { return Ok(Value::Undefined) }; + if arg(args, 0).truthy() { + set_slot(i, list, SELECTION, Value::Number(index as f64))?; + } else if selection_index(i, list)? == Some(index) { + set_slot(i, list, SELECTION, Value::Number(-1.0))?; + } + Ok(Value::Undefined) +} + +fn item_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + item_place(i, &this, "toString")?; + let text = i.get_value(&this, &key("text"))?; + Ok(Value::String(i.to_str(&text)?)) +} + +/// `list.removeAll()`. +fn remove_all(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let o = list_of(i, &this, "removeAll")?; + let n = items_of(i, o)?.len() as f64; + let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a list without its window".into())) }; + let count = number_slot(i, win, ITEM_COUNT)?; + set_slot(i, win, ITEM_COUNT, Value::Number((count - n).max(0.0)))?; + let kept = list(i, &[], false)?; + set_slot(i, o, ITEMS, Value::Object(kept))?; + let items = list(i, &[], true)?; + set_open(i, o, "items", Value::Object(items))?; + set_slot(i, o, SELECTION, Value::Number(-1.0))?; + Ok(Value::Undefined) +} + +fn kids_of(i: &Interp, o: ObjId) -> JsResult> { + match object_slot(i, o, KIDS)? { + Some(a) => list_values(i, a), + None => Ok(Vec::new()), + } +} + +/// `findElement(name)`: the first control in the element, in order, whose `name` is `name`. +fn find_element(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "findElement")?; + let want = i.to_str(&arg(args, 0))?; + let mut stack: Vec = kids_of(i, o)?.into_iter().rev().collect(); + while let Some(v) = stack.pop() { + i.use_fuel()?; + let Some(c) = v.as_object() else { continue }; + let name = i.get_value(&v, &key("name"))?; + if matches!(&name, Value::String(s) if *s == want) { + return Ok(v); + } + stack.extend(kids_of(i, c)?.into_iter().rev()); + } + Ok(Value::Null) +} + +/// Calls the element's handler `name` when it has one. → its result, or `None` without one. +fn handler(i: &mut Interp, o: ObjId, name: &str) -> JsResult> { + let f = i.get_value(&Value::Object(o), &key(name))?; + if !i.is_callable(&f) { + return Ok(None); + } + i.call(&f, &Value::Object(o), &[]).map(Some) +} + +/// `notify([event])`: runs the control's `onClick`, `onChange` or `onChanging`. +fn notify(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, kind) = element(i, &this, "notify")?; + let event = match arg(args, 0) { + Value::Undefined if matches!(kind.as_str(), "button" | "checkbox" | "radiobutton") => "onClick".to_string(), + Value::Undefined => "onChange".to_string(), + v => i.to_str(&v)?.to_rust_string(), + }; + if !matches!(event.as_str(), "onClick" | "onChange" | "onChanging") { + return Err(error(i, "notify: give onClick, onChange or onChanging")); + } + handler(i, o, &event)?; + Ok(Value::Undefined) +} + +fn control_show(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "show")?; + i.put(o, key("visible"), Value::Bool(true), true)?; + Ok(Value::Undefined) +} + +fn control_hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "hide")?; + i.put(o, key("visible"), Value::Bool(false), true)?; + Ok(Value::Undefined) +} + +fn nothing(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Undefined) +} + +fn dialog_of(i: &mut Interp, this: &Value, what: &str) -> JsResult { + match kind_of(i, this)? { + Some((o, kind)) if kind == "dialog" => Ok(o), + _ => Err(i.type_error(&format!("{what}: this is not a ScriptUI window"))), + } +} + +/// `close([result])`: closes the dialog that is showing once the running handler returns. +fn close(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = dialog_of(i, &this, "close")?; + let result = match arg(args, 0) { + Value::Undefined => 0.0, + v => number_arg(i, &v, "close: the result")?, + }; + if classes(i)?.showing == Some(o) { + set_slot(i, o, CLOSING, Value::Number(result))?; + } + Ok(Value::Undefined) +} + +/// `hide()`: closes the dialog that is showing with the result 0. +fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + close(i, this, &[], false) +} + +fn host_fn(i: &mut Interp, name: &str) -> JsResult { + let host = classes(i)?.host; + i.get_value(&Value::Object(host), &key(name)) +} + +fn set_showing(i: &mut Interp, showing: Option) { + if let Some(c) = i.script_ui.as_mut() { + c.showing = showing; + } +} + +/// `show()` on a dialog: gives its description to the host's `open`, then runs it ([`opened`]). +fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult { + let win = dialog_of(i, &this, "show")?; + match classes(i)?.showing { + Some(o) if o == win => return Err(error(i, "show: this dialog is already showing")), + Some(_) => return Err(error(i, "show: a dialog cannot open while another dialog is showing")), + None => {} + } + set_showing(i, Some(win)); + set_slot(i, win, CLOSING, Value::Undefined)?; + let described = describe(i, win); + let (desc, nodes, def, cancel) = match described { + Ok(d) => d, + Err(e) => { + set_showing(i, None); + return Err(e); + } + }; + let open = host_fn(i, "open")?; + Ok(Pause { + host: open, + args: vec![desc], + keep: vec![Value::Object(win), Value::Object(nodes), Value::Number(def), Value::Number(cancel)], + resume: opened, + failed: Some(failed), + }) +} + +/// A host call of `show()` failed, or a handler threw: the dialog is no longer showing. +fn failed(i: &mut Interp, keep: &[Value]) { + let Some(win) = arg(keep, 0).as_object() else { return }; + if classes(i).ok().and_then(|c| c.showing) != Some(win) { + return; + } + set_showing(i, None); + if let Ok(end) = host_fn(i, "end") { + let _ = i.call(&end, &Value::Undefined, &[Value::Number(0.0), Value::Bool(false)]); + } +} + +/// `show()` ends with `result`. +fn finish(i: &mut Interp, win: ObjId, result: f64) -> JsResult { + set_showing(i, None); + set_slot(i, win, CLOSING, Value::Undefined)?; + let end = host_fn(i, "end")?; + i.call(&end, &Value::Undefined, &[Value::Number(result), Value::Bool(true)])?; + Ok(Value::Number(result)) +} + +/// Runs `onClose`. → false when it returned `false`. +fn may_close(i: &mut Interp, win: ObjId) -> JsResult { + Ok(!matches!(handler(i, win, "onClose")?, Some(Value::Bool(false)))) +} + +/// Closes the dialog when a handler asked to, or asks the host's `wait` what happens next. +fn next(i: &mut Interp, win: ObjId) -> JsResult { + loop { + i.use_fuel()?; + if let Value::Number(result) = slot(i, win, CLOSING)? { + set_slot(i, win, CLOSING, Value::Undefined)?; + if may_close(i, win)? { + return finish(i, win, result); + } + continue; + } + let (desc, nodes, def, cancel) = describe(i, win)?; + let wait = host_fn(i, "wait")?; + i.again = Some(Pause { + host: wait, + args: vec![desc], + keep: vec![Value::Object(win), Value::Object(nodes), Value::Number(def), Value::Number(cancel)], + resume: answered, + failed: Some(failed), + }); + return Ok(Value::Undefined); + } +} + +/// Runs `r`; when it fails, the dialog is no longer showing. +fn guarded(i: &mut Interp, keep: &[Value], r: impl FnOnce(&mut Interp) -> JsResult) -> JsResult { + let v = r(i); + if v.is_err() { + failed(i, keep); + } + v +} + +fn opened(i: &mut Interp, keep: &[Value], _: Value) -> JsResult { + guarded(i, keep, |i| { + let Some(win) = arg(keep, 0).as_object() else { return Err(Abrupt::Internal("show lost its dialog".into())) }; + handler(i, win, "onShow")?; + next(i, win) + }) +} + +/// What the host's `wait` gave: the event, which the dialog takes, and what happens next. +fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { + guarded(i, keep, |i| { + let (Some(win), Some(nodes)) = (arg(keep, 0).as_object(), arg(keep, 1).as_object()) else { + return Err(Abrupt::Internal("show lost its dialog".into())); + }; + let Some(ev) = answer.as_object() else { return Err(Abrupt::Internal("the host gave show no event".into())) }; + let event = match slot(i, ev, "event")? { + Value::String(s) => s.to_rust_string(), + _ => String::new(), + }; + if event == "close" { + if may_close(i, win)? { + return finish(i, win, 0.0); + } + return next(i, win); + } + let id = match slot(i, ev, "id")? { + Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => n as usize, + _ => return Err(Abrupt::Internal("the host gave show an event without a control".into())), + }; + let nodes = list_values(i, nodes)?; + let Some((c, kind)) = nodes.get(id).map(|v| kind_of(i, v)).transpose()?.flatten() else { + return Err(Abrupt::Internal("the host gave show an event for a control the dialog does not hold".into())); + }; + let value = slot(i, ev, "value")?; + match event.as_str() { + "click" => { + if kind == "checkbox" { + let on = i.get_value(&Value::Object(c), &key("value"))?.truthy(); + i.put(c, key("value"), Value::Bool(!on), true)?; + } else if kind == "radiobutton" { + let parent = object_slot(i, c, PARENT)?; + for other in parent.map(|p| kids_of(i, p)).transpose()?.unwrap_or_default() { + if !same(&other, &Value::Object(c)) + && let Some((o, k)) = kind_of(i, &other)? + && k == "radiobutton" + { + i.put(o, key("value"), Value::Bool(false), true)?; + } + } + i.put(c, key("value"), Value::Bool(true), true)?; + } + if handler(i, c, "onClick")?.is_none() && kind == "button" { + let is = |k: usize| matches!(arg(keep, k), Value::Number(n) if n == id as f64); + if is(2) { + set_slot(i, win, CLOSING, Value::Number(1.0))?; + } else if is(3) { + set_slot(i, win, CLOSING, Value::Number(2.0))?; + } + } + } + "change" => { + match kind.as_str() { + "edittext" => { + i.put(c, key("text"), value, true)?; + handler(i, c, "onChanging")?; + } + "slider" => { + i.put(c, key("value"), value, true)?; + handler(i, c, "onChanging")?; + } + _ => { + let n = match value { + Value::Number(n) => n, + _ => -1.0, + }; + set_slot(i, c, SELECTION, Value::Number(n))?; + } + } + handler(i, c, "onChange")?; + } + _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), + } + next(i, win) + }) +} + +fn text_of(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let s = i.to_str(v)?; + let text = if s.len() > MAX_TEXT_BYTES { None } else { Some(s.to_rust_string()) }; + match text { + Some(t) if t.len() <= MAX_TEXT_BYTES => Ok(t), + _ => Err(range(i, &format!("show: {what} is longer than 16 KiB"))), + } +} + +fn get(i: &mut Interp, o: ObjId, name: &str) -> JsResult { + i.get_value(&Value::Object(o), &key(name)) +} + +fn number_of(i: &mut Interp, o: ObjId, name: &str) -> JsResult { + let v = get(i, o, name)?; + Ok(Data::Number(number_arg(i, &v, &format!("show: a control's {name}"))?)) +} + +/// An alignment: a name, or an array of a horizontal and a vertical name; `null` when not set. +fn alignment(i: &mut Interp, v: &Value) -> JsResult { + match v { + Value::Undefined | Value::Null => Ok(Data::Null), + Value::Object(a) if matches!(i.object(*a)?.class, Class::Array { .. }) => { + let mut out = Vec::new(); + for n in 0..2 { + let part = i.get_value(v, &index_key(n))?; + out.push(Data::String(text_of(i, &part, "an alignment")?.to_lowercase())); + } + Ok(Data::Array(out)) + } + v => Ok(Data::String(text_of(i, v, "an alignment")?.to_lowercase())), + } +} + +/// Numbers read from `v`'s indices, or else from its properties `names`. +fn numbers(i: &mut Interp, v: &Value, names: &[&str], what: &str) -> JsResult { + let Some(o) = v.as_object() else { + if matches!(v, Value::Undefined | Value::Null) { + return Ok(Data::Null); + } + return Err(i.type_error(&format!("show: give {what} as an array or an object"))); + }; + let array = matches!(i.object(o)?.class, Class::Array { .. }); + let mut out = Vec::new(); + for (n, name) in names.iter().enumerate() { + let part = if array { i.get_value(v, &index_key(n as u32))? } else { i.get_value(v, &key(name))? }; + out.push(Data::Number(number_arg(i, &part, &format!("show: {what}"))?)); + } + Ok(Data::Array(out)) +} + +/// Bounds as `[left, top, right, bottom]`: from an array, from `x`, `y`, `width` and `height`, or +/// from `left`, `top`, `right` and `bottom`. +fn bounds(i: &mut Interp, v: &Value) -> JsResult { + if let Some(o) = v.as_object() + && !matches!(i.object(o)?.class, Class::Array { .. }) + && !matches!(i.get_value(v, &key("width"))?, Value::Undefined) + { + let Data::Array(xywh) = numbers(i, v, &["x", "y", "width", "height"], "bounds")? else { return Ok(Data::Null) }; + let n = |k: usize| match xywh.get(k) { + Some(Data::Number(n)) => *n, + _ => 0.0, + }; + return Ok(Data::Array(vec![Data::Number(n(0)), Data::Number(n(1)), Data::Number(n(0) + n(2)), Data::Number(n(1) + n(3))])); + } + numbers(i, v, &["left", "top", "right", "bottom"], "bounds") +} + +fn margins(i: &mut Interp, v: &Value) -> JsResult { + if v.as_object().is_some() { + return numbers(i, v, &["left", "top", "right", "bottom"], "margins"); + } + let m = number_arg(i, v, "show: margins")?; + Ok(Data::Array(vec![Data::Number(m); 4])) +} + +/// The dialog's description: its elements in order, each after the container that holds it, as +/// [`Data`] for the host's `open` and `wait`, with the elements in that order, and the indices of +/// its default and cancel elements (-1 for none). +fn describe(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f64)> { + let mark = i.temp_roots.len(); + let r = describe_rooted(i, win); + i.temp_roots.truncate(mark); + r +} + +fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f64)> { + let mut order: Vec<(ObjId, String, f64)> = Vec::new(); + let mut seen = std::collections::HashSet::new(); + let mut stack: Vec<(Value, f64, usize)> = vec![(Value::Object(win), -1.0, 0)]; + while let Some((v, parent, depth)) = stack.pop() { + i.use_fuel()?; + let Some((o, kind)) = kind_of(i, &v)? else { return Err(i.type_error("show: the dialog holds something that is not a control")) }; + if !seen.insert(o) { + return Err(i.type_error("show: a control appears twice in the dialog")); + } + if order.len() > MAX_CONTROLS { + return Err(range(i, &format!("show: a dialog can hold at most {MAX_CONTROLS} controls"))); + } + if depth > MAX_DEPTH { + return Err(range(i, &format!("show: controls can be nested at most {MAX_DEPTH} deep"))); + } + let index = order.len() as f64; + order.push((o, kind, parent)); + for kid in kids_of(i, o)?.into_iter().rev() { + stack.push((kid, index, depth + 1)); + } + } + let objects: Vec = order.iter().map(|(o, ..)| Value::Object(*o)).collect(); + i.temp_roots.extend(objects.iter().cloned()); + let mut nodes = Vec::with_capacity(order.len()); + let mut names = Vec::with_capacity(order.len()); + let mut items_total = 0usize; + for (o, kind, parent) in &order { + let o = *o; + let name_v = get(i, o, "name")?; + let name = text_of(i, &name_v, "a control's name")?; + let text_v = get(i, o, "text")?; + let text = text_of(i, &text_v, "a control's text")?; + let mut d: Vec<(String, Data)> = vec![ + ("kind".into(), Data::String(kind.clone())), + ("parent".into(), Data::Number(*parent)), + ("name".into(), Data::String(name.clone())), + ("text".into(), Data::String(text.clone())), + ]; + names.push((kind.clone(), name, text)); + let enabled = get(i, o, "enabled")?.truthy(); + let visible = get(i, o, "visible")?.truthy(); + d.push(("enabled".into(), Data::Bool(enabled))); + d.push(("visible".into(), Data::Bool(visible))); + let b = get(i, o, "bounds")?; + d.push(("bounds".into(), bounds(i, &b)?)); + let size = get(i, o, "preferredSize")?; + d.push(("size".into(), numbers(i, &size, &["width", "height"], "preferredSize")?)); + let a = get(i, o, "alignment")?; + d.push(("alignment".into(), alignment(i, &a)?)); + if matches!(kind.as_str(), "dialog" | "group" | "panel") { + let orientation = get(i, o, "orientation")?; + d.push(("orientation".into(), Data::String(text_of(i, &orientation, "an orientation")?.to_lowercase()))); + let ac = get(i, o, "alignChildren")?; + d.push(("alignChildren".into(), alignment(i, &ac)?)); + d.push(("spacing".into(), number_of(i, o, "spacing")?)); + let m = get(i, o, "margins")?; + d.push(("margins".into(), margins(i, &m)?)); + } + match kind.as_str() { + "checkbox" | "radiobutton" => { + let on = get(i, o, "value")?.truthy(); + d.push(("value".into(), Data::Bool(on))); + } + "slider" | "progressbar" => { + d.push(("value".into(), number_of(i, o, "value")?)); + d.push(("minvalue".into(), number_of(i, o, "minvalue")?)); + d.push(("maxvalue".into(), number_of(i, o, "maxvalue")?)); + } + "edittext" => { + let props = get(i, o, "properties")?; + let (multiline, readonly) = match props { + Value::Object(_) => (i.get_value(&props, &key("multiline"))?.truthy(), i.get_value(&props, &key("readonly"))?.truthy()), + _ => (false, false), + }; + d.push(("multiline".into(), Data::Bool(multiline))); + d.push(("readonly".into(), Data::Bool(readonly))); + } + "dropdownlist" | "listbox" => { + let items = items_of(i, o)?; + items_total = items_total.saturating_add(items.len()); + if items_total > MAX_ITEMS { + return Err(range(i, &format!("show: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + let mut texts = Vec::with_capacity(items.len()); + for item in &items { + let t = i.get_value(item, &key("text"))?; + texts.push(Data::String(text_of(i, &t, "a list item's text")?)); + } + d.push(("items".into(), Data::Array(texts))); + let sel = selection_index(i, o)?.filter(|n| *n < items.len()); + d.push(("selection".into(), sel.map_or(Data::Null, |n| Data::Number(n as f64)))); + } + _ => {} + } + nodes.push(Data::Object(d)); + } + let target = |i: &mut Interp, name: &str, word: &str| -> JsResult { + let given = get(i, win, name)?; + if let Some(n) = objects.iter().position(|o| same(o, &given)) { + return Ok(n as f64); + } + if !matches!(given, Value::Undefined | Value::Null) { + return Ok(-1.0); + } + let button = |by_name: bool| names.iter().position(|(k, n, t)| k == "button" && (if by_name { n } else { t }).to_lowercase() == word); + Ok(button(true).or_else(|| button(false)).map_or(-1.0, |n| n as f64)) + }; + let def = target(i, "defaultElement", "ok")?; + let cancel = target(i, "cancelElement", "cancel")?; + let desc = Data::Object(vec![ + ("nodes".into(), Data::Array(nodes)), + ("defaultElement".into(), Data::Number(def)), + ("cancelElement".into(), Data::Number(cancel)), + ]); + let desc = i.write_data(desc, 0, true)?; + i.temp_roots.push(desc.clone()); + let kept = list(i, &objects, false)?; + Ok((desc, kept, def, cancel)) +} + +/// Adds `Window`, its prototype's methods, and the host functions in `items`. +pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResult<()> { + let host = i.host_object("Window", items)?; + let object_proto = i.intrinsics.object_proto; + i.rooted(&[Value::Object(host)], |i| { + i.reserve_heap(OBJECT_BYTES.saturating_mul(4))?; + let window_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(window_proto)); + let control_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(control_proto)); + let item_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(item_proto)); + let layout = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(layout)); + let selection_get = native(i, "selection", selection_get, 0, NativeKind::Plain, false)?; + i.temp_roots.push(Value::Object(selection_get)); + let selection_set = native(i, "selection", selection_set, 1, NativeKind::Plain, false)?; + i.temp_roots.push(Value::Object(selection_set)); + i.script_ui = Some(Classes { window_proto, control_proto, item_proto, layout, host, selection_get, selection_set, showing: None }); + let window = native(i, "Window", window_ctor, 4, NativeKind::Plain, true)?; + constructor(i, "Window", window, window_proto)?; + method(i, window_proto, "add", add, 4)?; + method(i, window_proto, "findElement", find_element, 1)?; + method(i, window_proto, "close", close, 1)?; + method(i, window_proto, "hide", hide, 0)?; + method(i, window_proto, "center", nothing, 1)?; + pausable_method(i, window_proto, "show", show, 0)?; + method(i, control_proto, "add", add, 4)?; + method(i, control_proto, "findElement", find_element, 1)?; + method(i, control_proto, "removeAll", remove_all, 0)?; + method(i, control_proto, "notify", notify, 1)?; + method(i, control_proto, "show", control_show, 0)?; + method(i, control_proto, "hide", control_hide, 0)?; + method(i, item_proto, "toString", item_to_string, 0)?; + let index = native(i, "index", item_index, 0, NativeKind::Plain, false)?; + i.define(item_proto, key("index"), Prop::Accessor { get: Some(index), set: None, flags: 0 })?; + let get = native(i, "selected", item_selected_get, 0, NativeKind::Plain, false)?; + let set = native(i, "selected", item_selected_set, 1, NativeKind::Plain, false)?; + i.define(item_proto, key("selected"), Prop::Accessor { get: Some(get), set: Some(set), flags: 0 })?; + method(i, layout, "layout", nothing, 1)?; + method(i, layout, "resize", nothing, 0)?; + i.object_mut(layout)?.extensible = false; + Ok(()) + }) +} diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs new file mode 100644 index 0000000000..18067d6375 --- /dev/null +++ b/crates/js/src/scriptui_tests.rs @@ -0,0 +1,309 @@ +//! ScriptUI's `Window`: building a dialog, its description, the events a host gives `show()`, the +//! handlers they run, and the limits on what a dialog may hold. + +use std::cell::RefCell; +use std::collections::VecDeque; +use std::rc::Rc; + +use super::*; + +/// What the host was given: each description, and each `end`'s result and whether it was normal. +#[derive(Default)] +struct Seen { + descriptions: Vec, + ends: Vec<(f64, bool)>, +} + +/// The events `wait` has left to give. +type Queue = Rc>>; + +/// A realm whose `wait` gives the events in `events`, in order, and throws when none is left +/// (or waits, where the run can). +fn realm(events: Vec) -> (Realm, Rc>, Queue) { + let mut r = Realm::new(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + let seen: Rc> = Rc::default(); + let queue = Rc::new(RefCell::new(VecDeque::from(events))); + let can_wait = r.wait_flag(); + let s = seen.clone(); + let open: HostFunction = Rc::new(move |args| { + s.borrow_mut().descriptions.push(args.into_iter().next().unwrap_or(Data::Undefined)); + Ok(Data::Undefined) + }); + let s = seen.clone(); + let q = queue.clone(); + let wait: HostFunction = Rc::new(move |args| { + s.borrow_mut().descriptions.push(args.into_iter().next().unwrap_or(Data::Undefined)); + match q.borrow_mut().pop_front() { + Some(e) => Ok(e), + None if can_wait.get() => Err(HostError::Wait), + None => Err(HostError::Error("no event left".into())), + } + }); + let s = seen.clone(); + let end: HostFunction = Rc::new(move |args| { + let n = match args.first() { + Some(Data::Number(n)) => *n, + _ => f64::NAN, + }; + s.borrow_mut().ends.push((n, matches!(args.get(1), Some(Data::Bool(true))))); + Ok(Data::Undefined) + }); + let items = vec![("open".into(), HostItem::Function(open)), ("wait".into(), HostItem::Function(wait)), ("end".into(), HostItem::Function(end))]; + r.define_script_ui(items).unwrap(); + (r, seen, queue) +} + +fn click(id: usize) -> Data { + Data::Object(vec![("event".into(), Data::String("click".into())), ("id".into(), Data::Number(id as f64))]) +} + +fn change(id: usize, value: Data) -> Data { + Data::Object(vec![("event".into(), Data::String("change".into())), ("id".into(), Data::Number(id as f64)), ("value".into(), value)]) +} + +fn close() -> Data { + Data::Object(vec![("event".into(), Data::String("close".into()))]) +} + +fn field<'a>(d: &'a Data, name: &str) -> &'a Data { + match d { + Data::Object(fields) => fields.iter().find(|(k, _)| k == name).map_or(&Data::Undefined, |(_, v)| v), + _ => &Data::Undefined, + } +} + +fn nodes(d: &Data) -> Vec { + match field(d, "nodes") { + Data::Array(a) => a.clone(), + _ => Vec::new(), + } +} + +/// Every built control, in the order the description lists them: 0 is the dialog. +const FORM: &str = r#" + var w = new Window("dialog", "Form"); + var g = w.add("group"); + var label = g.add("statictext", undefined, "Name:"); + var name = g.add("edittext", undefined, "first"); + var p = w.add("panel", undefined, "Options"); + var check = p.add("checkbox", undefined, "Bold"); + var r1 = p.add("radiobutton", undefined, "A"); + var r2 = p.add("radiobutton", undefined, "B"); + var drop = p.add("dropdownlist", undefined, ["x", "y", "z"]); + var box = p.add("listbox", undefined, ["one", "two"]); + var slide = p.add("slider", undefined, 5, 0, 10); + var bar = p.add("progressbar", undefined, 3, 10); + var ok = w.add("button", undefined, "OK"); + var cancel = w.add("button", undefined, "Cancel", {name: "cancel"}); +"#; + +#[test] +fn a_dialog_with_each_control_gives_back_the_values_the_person_set() { + let events = vec![ + change(3, Data::String("second".into())), + click(5), + click(6), + click(7), + change(8, Data::Number(2.0)), + change(9, Data::Number(1.0)), + change(10, Data::Number(7.5)), + click(12), + ]; + let (mut r, seen, _) = realm(events); + let source = format!( + "{FORM} var result = w.show(); [result, name.text, check.value, r1.value, r2.value, drop.selection.text, box.selection.index, slide.value, bar.value].join('|')" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("1|second|true|false|true|z|1|7.5|3".into())); + let seen = seen.borrow(); + let first = nodes(&seen.descriptions[0]); + let kinds: Vec = first + .iter() + .map(|n| match field(n, "kind") { + Data::String(s) => s.clone(), + _ => String::new(), + }) + .collect(); + let want = [ + "dialog", + "group", + "statictext", + "edittext", + "panel", + "checkbox", + "radiobutton", + "radiobutton", + "dropdownlist", + "listbox", + "slider", + "progressbar", + "button", + "button", + ]; + assert_eq!(kinds, want); + assert_eq!(field(&first[3], "parent"), &Data::Number(1.0), "the field is in the group"); + assert_eq!(field(&first[8], "items"), &Data::Array(vec![Data::String("x".into()), Data::String("y".into()), Data::String("z".into())])); + assert_eq!(field(&first[10], "maxvalue"), &Data::Number(10.0)); + assert_eq!(field(&seen.descriptions[0], "defaultElement"), &Data::Number(12.0), "OK is the default element by its text"); + assert_eq!(field(&seen.descriptions[0], "cancelElement"), &Data::Number(13.0), "Cancel is the cancel element by its name"); + assert_eq!(seen.ends, vec![(1.0, true)]); +} + +#[test] +fn the_default_and_cancel_buttons_close_with_1_and_2_and_a_close_gives_0() { + for (event, want) in [(click(12), 1.0), (click(13), 2.0), (close(), 0.0)] { + let (mut r, _, _) = realm(vec![event]); + assert_eq!(r.run(&format!("{FORM} w.show()")).unwrap(), JsValue::Number(want)); + } +} + +#[test] +fn a_button_with_a_handler_does_not_close_the_dialog() { + let (mut r, _, _) = realm(vec![click(12), click(13)]); + let source = format!("{FORM} var clicks = 0; ok.onClick = function () {{ clicks++; }}; [w.show(), clicks].join()"); + assert_eq!(r.run(&source).unwrap(), JsValue::String("2,1".into())); +} + +#[test] +fn close_gives_its_result_and_on_close_can_keep_the_dialog_open() { + let (mut r, seen, _) = realm(vec![click(5), click(5)]); + let source = format!( + "{FORM} var asked = 0; check.onClick = function () {{ w.close(7); }}; w.onClose = function () {{ asked++; return asked > 1; }}; [w.show(), asked].join()" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("7,2".into())); + assert_eq!(seen.borrow().ends, vec![(7.0, true)]); +} + +#[test] +fn close_in_on_show_ends_show_without_waiting() { + let (mut r, seen, _) = realm(Vec::new()); + assert_eq!(r.run(&format!("{FORM} w.onShow = function () {{ w.close(4); }}; w.show()")).unwrap(), JsValue::Number(4.0)); + assert_eq!(seen.borrow().descriptions.len(), 1, "only open saw the dialog"); +} + +#[test] +fn handlers_change_other_controls_and_the_next_description_shows_it() { + let (mut r, seen, _) = realm(vec![click(5), click(12)]); + let source = + format!("{FORM} check.onClick = function () {{ name.text = check.value ? 'on' : 'off'; slide.enabled = false; }}; w.show(); name.text"); + assert_eq!(r.run(&source).unwrap(), JsValue::String("on".into())); + let seen = seen.borrow(); + let after = nodes(&seen.descriptions[2]); + assert_eq!(field(&after[3], "text"), &Data::String("on".into())); + assert_eq!(field(&after[10], "enabled"), &Data::Bool(false)); +} + +#[test] +fn on_change_runs_after_on_changing() { + let (mut r, _, _) = realm(vec![change(3, Data::String("x".into())), click(12)]); + let source = format!( + "{FORM} var log = []; name.onChanging = function () {{ log.push('changing ' + name.text); }}; name.onChange = function () {{ log.push('change'); }}; w.show(); log.join()" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("changing x,change".into())); +} + +#[test] +fn a_handler_that_loops_ends_the_run_at_its_fuel() { + let (mut r, seen, _) = realm(vec![click(5)]); + r.set_limits(Limits { fuel: 200_000, ..Limits::default() }); + let e = r.run(&format!("{FORM} check.onClick = function () {{ for (;;) {{}} }}; w.show()")).unwrap_err(); + assert!(matches!(e.kind, RunErrorKind::Limit(_)), "{e:?}"); + assert_eq!(seen.borrow().ends, vec![(0.0, false)], "show ended without its result"); +} + +#[test] +fn a_dialog_cannot_be_shown_inside_its_own_or_another_show() { + let (mut r, _, _) = realm(vec![click(5), click(12)]); + let source = format!( + "{FORM} var errors = []; check.onClick = function () {{ try {{ w.show(); }} catch (e) {{ errors.push(e.message); }} try {{ new Window('dialog').show(); }} catch (e) {{ errors.push(e.message); }} }}; w.show(); errors.join('|')" + ); + assert_eq!( + r.run(&source).unwrap(), + JsValue::String("show: this dialog is already showing|show: a dialog cannot open while another dialog is showing".into()) + ); +} + +#[test] +fn a_dialog_can_be_shown_again_after_it_closed() { + let (mut r, _, _) = realm(vec![click(12), click(13)]); + assert_eq!(r.run(&format!("{FORM} [w.show(), w.show()].join()")).unwrap(), JsValue::String("1,2".into())); +} + +#[test] +fn types_that_are_not_available_yet_throw_errors_that_say_so() { + for (source, want) in [ + ("new Window('palette')", "Window: a window of type palette is not available yet; use dialog"), + ("new Window('dialog { b: Button {} }')", "Window: resource specifications are not available yet; build the dialog with add()"), + ("new Window('dialog').add('tabbedpanel')", "add: the control type tabbedpanel is not available yet"), + ("new Window('dialog').add('wobble')", "add: there is no control type wobble"), + ("new Window('dialog').add('button').add('button')", "add: a button holds no controls"), + ( + "new Window('dialog').add('listbox', undefined, [], {multiselect: true})", + "add: a list box that selects several items is not available yet", + ), + ] { + let (mut r, _, _) = realm(Vec::new()); + let e = r.run(&format!("try {{ {source}; 'made' }} catch (e) {{ e.message }}")).unwrap(); + assert_eq!(e, JsValue::String(want.into()), "{source}"); + } +} + +#[test] +fn too_many_controls_too_deep_a_nesting_and_too_long_a_text_are_refused() { + let (mut r, _, _) = realm(Vec::new()); + let many = + r.run("var w = new Window('dialog'); try { for (var i = 0; i < 100000; i++) w.add('button'); } catch (e) { [e.name, i].join() }").unwrap(); + assert_eq!(many, JsValue::String(format!("RangeError,{}", scriptui::MAX_CONTROLS))); + let deep = + r.run("var c = new Window('dialog'); try { for (var d = 0; d < 1000; d++) c = c.add('group'); } catch (e) { [e.name, d].join() }").unwrap(); + assert_eq!(deep, JsValue::String(format!("RangeError,{}", scriptui::MAX_DEPTH))); + let items = r.run("var l = new Window('dialog').add('dropdownlist'); try { for (var n = 0; n < 5000; n++) l.add('item', n); } catch (e) { [e.name, n].join() }").unwrap(); + assert_eq!(items, JsValue::String(format!("RangeError,{}", scriptui::MAX_ITEMS))); + let long = r + .run("var w = new Window('dialog'); w.add('statictext', undefined, new Array(20000).join('x')); try { w.show(); } catch (e) { e.message }") + .unwrap(); + assert_eq!(long, JsValue::String("show: a control's text is longer than 16 KiB".into())); +} + +#[test] +fn a_bounds_value_that_is_not_finite_is_refused_when_shown() { + let (mut r, _, _) = realm(Vec::new()); + let v = r.run("var w = new Window('dialog'); w.add('button', [0, 0, Infinity, 20]); try { w.show(); } catch (e) { e.name }").unwrap(); + assert_eq!(v, JsValue::String("RangeError".into())); +} + +#[test] +fn a_script_cannot_change_a_dialog_s_controls_behind_its_back() { + let (mut r, _, _) = realm(vec![click(1)]); + let source = "var w = new Window('dialog'); var b = w.add('button', undefined, 'OK'); \ + w.children.push(w); w.__vcKids = []; try { w.__vcKids.push(w); } catch (e) {} b.__vcKind = 'dialog'; w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(1.0)); +} + +#[test] +fn a_show_that_waits_resumes_with_the_host_s_answer() { + let (mut r, seen, queue) = realm(Vec::new()); + r.start(&format!("{FORM} check.onClick = function () {{ name.text = 'clicked'; }}; var n = w.show(); n + ':' + name.text")).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Paused); + assert!(r.waits(), "show waits at open's first wait"); + r.answer(click(5)).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Paused); + assert!(r.waits(), "show waits again after the handler"); + queue.borrow_mut().push_back(click(12)); + r.answer(click(5)).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::String("1:clicked".into()))); + assert_eq!(seen.borrow().ends, vec![(1.0, true)]); +} + +#[test] +fn findelement_items_and_selection_follow_the_list() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var g = w.add('group'); var d = g.add('dropdownlist', undefined, [], {name: 'pick'}); \ + d.add('item', 'a'); var b = d.add('item', 'b'); d.selection = 1; var s1 = d.selection.text; b.selected = false; \ + var s2 = d.selection; d.selection = 0; d.removeAll(); [w.findElement('pick') === d, s1, s2, d.selection, d.items.length, String(b)].join()", + ) + .unwrap(); + assert_eq!(v, JsValue::String("true,b,,,0,b".into())); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a24755ab12..eba418f360 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -131,6 +131,7 @@ pub mod save_swatch_library; pub mod save_symbol_library; pub mod script_check; pub mod script_run; +pub mod script_window; pub mod shape_builder_options; pub(crate) mod shapes; pub mod shortcut_import; @@ -466,6 +467,7 @@ registry! { ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC, ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC, ScriptFiles: [script_run::PICKER_KIND] => script_run::PICKER_SPEC, + ScriptWindow: [script_window::KIND] => script_window::SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, ObjectMosaic: [object_mosaic::KIND] => object_mosaic::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, @@ -776,7 +778,7 @@ pub fn cancel(app: &mut VectorcraftApp) { if app.ui.dialog.as_mut().is_some_and(new_document::close_popup) { return; } - if let Some(d) = app.ui.dialog.take() { + if let Some(mut d) = app.ui.dialog.take() { if d.kind == "preferences" { crate::original_editor::cancel(app); } @@ -811,6 +813,9 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == script_run::PICKER_KIND { script_run::picker_cancel(app, &d); } + if d.kind == script_window::KIND { + script_window::cancel(app, &mut d); + } missing_links::cancelled(app, &d); // Cancel discards Recolor Artwork's own history of color edits with them. if d.kind == recolor::KIND { @@ -830,6 +835,11 @@ pub fn cancel(app: &mut VectorcraftApp) { let _ = app.session.cancel_interaction(); } app.ui.dialog = parent(&d); + // A script's ScriptUI dialog stays open, with the text typed in its fields, until the + // script closes it or the run no longer waits at it. + if d.kind == script_window::KIND && app.ui.dialog.is_none() && app.session.script_running() { + app.ui.dialog = Some(d); + } } settle(app); } diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index f8baa7b7de..fcf80916ae 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -194,9 +194,10 @@ fn close_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result } /// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which -/// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet. +/// Cancel shows again as it was, with the text typed in a ScriptUI dialog's fields. Any other open +/// dialog stays, and quitting asks nothing yet. pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { - let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND || d.kind == PICKER_KIND); + let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND || d.kind == PICKER_KIND || d.kind == super::script_window::KIND); if app.ui.dialog.is_some() { return; } @@ -218,6 +219,7 @@ pub(crate) fn settle_close(app: &mut VectorcraftApp) { app.ui.dialog = None; } else if app.session.script_dialog().is_none() && app.session.script_picker().is_none() + && app.session.script_window().is_none() && let Some(d) = app.ui.dialog.as_mut() { d.fields.remove(super::PARENT); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs new file mode 100644 index 0000000000..443f3e96cb --- /dev/null +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -0,0 +1,360 @@ +//! A dialog a script builds with ScriptUI's `new Window("dialog")` and shows with `show()` +//! (kind `scriptWindow`). It draws the controls the running script's dialog holds, at the places +//! the engine laid them out, and gives the script each click and change. +//! +//! Its fields are `title` and, for `ui.dialog.set` and `ui.dialog.confirm`, `event` (`click`, +//! `change` or `close`), `control` (a control's index in the dialog's list of elements, or its +//! name or text) and `value` (an edit field's text, a slider's number, or a list's item index or +//! null). `ui.dialog.confirm` gives the script that event and leaves the dialog open; an event the +//! dialog cannot take is an error. An edit field gives its text when it loses the keyboard focus, +//! when Enter is pressed in a one-line field, or before a click on another control or a close. Events given in +//! one frame reach the script one at a time, in order. Enter outside a field clicks the default button, +//! and Escape or `ui.dialog.cancel` clicks the cancel button, or closes the dialog when it has +//! none. Stop ends the run and puts back everything it did. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_engine::script::scriptui::UiNode; +use vectorcraft_engine::script::{ScriptUiDialog, UiEvent, UiKind, UiValue}; + +use super::{DialogAction, DialogSpec}; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of a script's ScriptUI dialog. +pub const KIND: &str = "scriptWindow"; + +/// The most of the dialog's content shown at once; a larger dialog scrolls. +const MAX_SHOWN: egui::Vec2 = egui::vec2(960.0, 640.0); + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading, + body_with_actions: Some(body), + confirm, + ok: None, + inputs: |_| &["event", "control", "value"], + min_width: 240.0, + max_width: Some(1000.0), + ..DialogSpec::FORM +}; + +/// Shows the ScriptUI dialog the running script waits at. +pub(crate) fn open(app: &mut VectorcraftApp, w: &ScriptUiDialog) { + app.ui.dialog = Some(Dialog::new(KIND, json!({"title": w.title(), SHOWN_KEY: w.shown}))); +} + +/// The field that holds which `show()` of the run the open dialog is for. +const SHOWN_KEY: &str = "shown"; + +/// Is `d` open for the dialog `w`, and not for one the script showed before it? +pub(crate) fn is_open_for(d: &Dialog, w: &ScriptUiDialog) -> bool { + d.kind == KIND && d.fields.get(SHOWN_KEY).and_then(Value::as_u64) == Some(w.shown) +} + +fn heading(d: &Dialog) -> String { + let title = d.str("title"); + if title.is_empty() { tl!("Script Alert").into() } else { vectorcraft_engine::script::dialogs::shown_text(&title, false) } +} + +fn memory_id() -> egui::Id { + egui::Id::unique("scriptWindow.shown") +} + +/// The dialog to draw: the one the run waits at, or while a handler runs, the one it last waited +/// at, with every control disabled. +fn shown(app: &VectorcraftApp, ctx: &egui::Context) -> Option<(Arc, bool)> { + if let Some(w) = app.session.script_window() { + let w = Arc::new(w); + ctx.data_mut(|m| m.insert_temp(memory_id(), w.clone())); + return Some((w, true)); + } + ctx.data(|m| m.get_temp::>(memory_id())).map(|w| (w, false)) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let Some((w, waiting)) = shown(app, ui.ctx()) else { return DialogAction::None }; + let mut events = Vec::new(); + let (width, height) = w.size(); + let size = egui::vec2(width.max(1.0), height.max(1.0)); + egui::ScrollArea::both().max_width(MAX_SHOWN.x).max_height(MAX_SHOWN.y).auto_shrink([true, true]).show(ui, |ui| { + let (area, _) = ui.allocate_exact_size(size, egui::Sense::hover()); + ui.add_enabled_ui(waiting, |ui| { + for (i, n) in w.nodes.iter().enumerate().skip(1) { + if n.visible + && let Some(e) = control(ui, d, area.min, i, n, w.default_element == Some(i)) + { + events.push(e); + } + } + }); + }); + ui.add_space(12.0); + let mut stop = false; + let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y); + ui.allocate_ui_with_layout(row, egui::Layout::left_to_right(egui::Align::Center), |ui| { + stop = widgets::secondary_button(ui, tl!("Stop")).clicked(); + }); + if stop { + app.session.script_request_stop(); + app.ui.dialog = None; + return DialogAction::None; + } + let typing = ui.ctx().memory(|m| m.focused().is_some()); + if events.is_empty() && waiting && !typing && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) { + events.extend(w.default_element.map(UiEvent::Click)); + } + if events.iter().any(|e| matches!(e, UiEvent::Click(_))) { + commit_drafts(&w, d, &mut events); + } + let mut queue: Vec = match d.fields.remove(QUEUE_KEY) { + Some(Value::Array(queue)) => queue, + _ => Vec::new(), + }; + queue.extend(events.iter().map(event_fields)); + if !waiting || queue.is_empty() { + if !queue.is_empty() { + d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); + } + return DialogAction::None; + } + let next = queue.remove(0); + if !queue.is_empty() { + d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); + } + if let Value::Object(fields) = next { + d.fields.extend(fields); + } + DialogAction::Confirm +} + +/// The field that holds the events the person gave in one frame that the script has not had yet; +/// the script takes one event each time it waits. +const QUEUE_KEY: &str = "queued"; + +/// Before a click or a close, gives the script the text typed in each edit field that has not left +/// the field yet, so the handler of a button that closes the dialog, or `onClose`, reads it. +pub(crate) fn commit_drafts(w: &ScriptUiDialog, d: &mut Dialog, events: &mut Vec) { + let mut changes = Vec::new(); + for (i, n) in w.nodes.iter().enumerate() { + if n.kind != UiKind::EditText || n.readonly || events.iter().any(|e| matches!(e, UiEvent::Change(c, _) if *c == i)) { + continue; + } + if let Some(Value::String(text)) = d.fields.remove(&draft_key(i)) + && text != n.text + { + changes.push(UiEvent::Change(i, UiValue::Text(text))); + } + } + let closing = |e: &UiEvent| matches!(e, UiEvent::Click(_) | UiEvent::Close); + events.sort_by_key(closing); + let at = events.iter().position(closing).unwrap_or(events.len()); + events.splice(at..at, changes); +} + +/// The field that holds an edit field's text while it is typed. +fn draft_key(i: usize) -> String { + format!("text{i}") +} + +/// Draws control `i` at its place from `origin`. → the event it gives. +fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, i: usize, n: &UiNode, default: bool) -> Option { + let rect = egui::Rect::from_min_size(origin + egui::vec2(n.rect.x, n.rect.y), egui::vec2(n.rect.w, n.rect.h)); + let t = Tokens::get(ui.ctx()); + let mut event = None; + ui.push_id(i, |ui| { + ui.add_enabled_ui(n.enabled, |ui| match n.kind { + UiKind::Dialog | UiKind::Group => {} + UiKind::Panel => { + let frame = rect.shrink(1.0); + let (enabled, name) = (ui.is_enabled(), n.text.clone()); + let r = ui.interact(rect, ui.scope_id().with("panel"), egui::Sense::hover()); + r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Group, enabled, &name)); + ui.painter().rect_stroke(frame, 4.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + if !n.text.is_empty() { + ui.painter().text(frame.min + egui::vec2(8.0, -6.0), egui::Align2::LEFT_TOP, &n.text, egui::FontId::proportional(11.0), t.text); + } + } + UiKind::StaticText => { + ui.put(rect, egui::Label::new(&n.text).wrap()); + } + UiKind::Button => { + let mut button = egui::Button::new(&n.text); + if default { + button = button.fill(t.accent_strong); + } + if ui.put(rect, button).clicked() { + event = Some(UiEvent::Click(i)); + } + } + UiKind::CheckBox => { + let mut on = n.checked; + if ui.put(rect, egui::Checkbox::new(&mut on, &n.text)).clicked() { + event = Some(UiEvent::Click(i)); + } + } + UiKind::RadioButton => { + if ui.put(rect, egui::RadioButton::new(n.checked, &n.text)).clicked() { + event = Some(UiEvent::Click(i)); + } + } + UiKind::EditText => event = edit(ui, d, rect, i, n), + UiKind::DropDownList => { + let shown = n.selection.and_then(|k| n.items.get(k)).cloned().unwrap_or_default(); + let mut picked = None; + ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { + craft_ui::ComboBox::from_id_salt(("script-window-list", i)).selected_text(shown).width(rect.width()).show_ui(ui, |ui| { + for (k, item) in n.items.iter().enumerate() { + if ui.selectable_label(n.selection == Some(k), item).clicked() { + picked = Some(k); + } + } + }); + }); + if let Some(k) = picked.filter(|k| n.selection != Some(*k)) { + event = Some(UiEvent::Change(i, UiValue::Index(Some(k)))); + } + } + UiKind::ListBox => { + ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + ui.scope_builder(egui::UiBuilder::new().max_rect(rect.shrink(3.0)), |ui| { + egui::ScrollArea::vertical().id_salt(("script-window-listbox", i)).max_height(rect.height() - 6.0).show(ui, |ui| { + for (k, item) in n.items.iter().enumerate() { + if ui.selectable_label(n.selection == Some(k), item).clicked() && n.selection != Some(k) { + event = Some(UiEvent::Change(i, UiValue::Index(Some(k)))); + } + } + }); + }); + } + UiKind::Slider => { + let mut v = n.value; + let r = ui.put(rect, egui::Slider::new(&mut v, n.min..=n.max).show_value(false)); + name_for_screen_readers(ui, &r, n); + if (r.drag_stopped() || (r.changed() && !r.dragged())) && v != n.value { + event = Some(UiEvent::Change(i, UiValue::Number(v))); + } + } + UiKind::ProgressBar => { + let span = n.max - n.min; + let part = if span > 0.0 { ((n.value - n.min) / span) as f32 } else { 0.0 }; + let r = ui.put(rect, egui::ProgressBar::new(part)); + name_for_screen_readers(ui, &r, n); + } + }); + }); + event +} + +/// Screen readers call a control with no visible label of its own (an edit field, a slider or a +/// progress bar) by the name the script gave it, or else a slider or progress bar by its text. +fn name_for_screen_readers(ui: &egui::Ui, r: &egui::Response, n: &UiNode) { + let label = if !n.name.is_empty() { + n.name.clone() + } else if n.kind != UiKind::EditText { + n.text.clone() + } else { + String::new() + }; + if !label.is_empty() { + ui.ctx().accesskit_node_builder(r.id, |node| node.set_label(label)); + } +} + +/// An edit field: its text is kept in the dialog while it is typed and given to the script when +/// the field loses the focus, or at Enter in a one-line field. +fn edit(ui: &mut egui::Ui, d: &mut Dialog, rect: egui::Rect, i: usize, n: &UiNode) -> Option { + let key = draft_key(i); + let mut text = d.fields.get(&key).and_then(Value::as_str).map_or_else(|| n.text.clone(), str::to_string); + let field = if n.multiline { egui::TextEdit::multiline(&mut text) } else { egui::TextEdit::singleline(&mut text) }; + let r = ui.put(rect, field.interactive(!n.readonly).desired_width(rect.width())); + name_for_screen_readers(ui, &r, n); + if r.changed() { + d.fields.insert(key.clone(), json!(text)); + } + let entered = !n.multiline && r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + if (r.lost_focus() || entered) && text != n.text && !n.readonly { + d.fields.remove(&key); + return Some(UiEvent::Change(i, UiValue::Text(text))); + } + if !r.has_focus() && !r.changed() { + d.fields.remove(&key); + } + None +} + +/// `event` as the dialog's `event`, `control` and `value` fields. +fn event_fields(event: &UiEvent) -> Value { + let (name, control, value) = match event { + UiEvent::Click(i) => ("click", json!(i), Value::Null), + UiEvent::Change(i, UiValue::Text(t)) => ("change", json!(i), json!(t)), + UiEvent::Change(i, UiValue::Number(v)) => ("change", json!(i), json!(v)), + UiEvent::Change(i, UiValue::Index(k)) => ("change", json!(i), json!(k)), + UiEvent::Close => ("close", Value::Null, Value::Null), + }; + json!({"event": name, "control": control, "value": value}) +} + +/// The event in the dialog's fields, for the dialog `w`. +fn event_of(w: &ScriptUiDialog, d: &Dialog) -> Result { + let control = match d.fields.get("control") { + Some(Value::Number(n)) => n.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("`control` must be a control's index, name or text")?, + Some(Value::String(s)) => { + w.find(s).ok_or_else(|| format!("the dialog has no control named {}", vectorcraft_engine::script::dialogs::cut_to(s, 64)))? + } + _ => 0, + }; + let list = w.nodes.get(control).is_some_and(|n| matches!(n.kind, UiKind::DropDownList | UiKind::ListBox)); + match (d.str("event").as_str(), d.fields.get("value")) { + ("close", _) => Ok(UiEvent::Close), + ("click", _) => Ok(UiEvent::Click(control)), + ("change", Some(Value::String(t))) => Ok(UiEvent::Change(control, UiValue::Text(t.clone()))), + ("change", Some(Value::Number(v))) if list => match v.as_u64() { + Some(k) => Ok(UiEvent::Change(control, UiValue::Index(Some(usize::try_from(k).unwrap_or(usize::MAX))))), + None => Err("a list's `value` must be an item index or null".into()), + }, + ("change", Some(Value::Number(v))) => Ok(UiEvent::Change(control, UiValue::Number(v.as_f64().unwrap_or(f64::NAN)))), + ("change", Some(Value::Null) | None) if list => Ok(UiEvent::Change(control, UiValue::Index(None))), + ("change", _) => Err("a change's `value` must be a string, a number or null".into()), + _ => Err("`event` must be click, change or close".into()), + } +} + +/// Gives the running script the event in the dialog's fields. The dialog stays open for the +/// script's next wait; an event it cannot take is an error. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let Some(w) = app.session.script_window() else { return Err("no script dialog waits".into()) }; + let event = event_of(&w, d)?; + app.session.script_window_answer(event)?; + if let Some(open) = app.ui.dialog.as_mut().filter(|open| open.kind == KIND) { + for k in ["event", "control", "value"] { + open.fields.remove(k); + } + } + Ok(Value::Null) +} + +/// Escape or `ui.dialog.cancel`: a click on the cancel button, or the close box when the dialog +/// has none or it cannot be clicked, after the text still typed in its fields. Events the script +/// has not had yet go after the ones before them. +pub(super) fn cancel(app: &mut VectorcraftApp, d: &mut Dialog) { + let Some(w) = app.session.script_window() else { return }; + let click = w.cancel_element.map(UiEvent::Click).filter(|e| vectorcraft_engine::script::scriptui::check_event(&w, e.clone()).is_ok()); + let mut events = vec![click.unwrap_or(UiEvent::Close)]; + commit_drafts(&w, d, &mut events); + let mut queue: Vec = match d.fields.remove(QUEUE_KEY) { + Some(Value::Array(queue)) => queue, + _ => Vec::new(), + }; + let mut events = events.into_iter(); + if queue.is_empty() + && let Some(first) = events.next() + { + let _ = app.session.script_window_answer(first); + } + queue.extend(events.map(|e| event_fields(&e))); + if !queue.is_empty() { + d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); + } +} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..9d442848ce 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6589,7 +6589,9 @@ liquify-list-end {0}, {1} {0} i {1} @msg is a confirm's answer, whose `value` must be true or false és la resposta d'un confirm, i el seu `value` ha de ser true o false @msg is longer than 16 KiB ocupa més de 16 KiB @msg is a prompt's answer, whose `value` must be a string or null és la resposta d'un prompt, i el seu `value` ha de ser una cadena o null -@msg must have `kind` alert, confirm or prompt ha de tenir `kind` alert, confirm o prompt +@msg must have `kind` alert, confirm, prompt or window ha de tenir `kind` alert, confirm, prompt o window +@msg is a window's answer, whose `value` must be a list of steps és la resposta d’una finestra, el `value` de la qual ha de ser una llista de passos +@msg has a step {i} that is not a valid click, change or close té un pas {i} que no és un clic, un canvi ni un tancament vàlid @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` només és per a una execució sense ningú a qui preguntar: a l'aplicació, la persona respon cada quadre de diàleg @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` ha de ser un nombre enter d’1 a {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` està imbricat en més de 64 nivells diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..ee8b68af7d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9868,7 +9868,9 @@ breakText Glyphs Glyfy @msg more than {MAX_IMPORT} presets více než {MAX_IMPORT} přednastavení @msg moved must be [[x,y]…] moved musí být [[x,y]…] @msg must be an object with `kind` and `value` musí být objekt s `kind` a `value` -@msg must have `kind` alert, confirm or prompt musí mít `kind` alert, confirm nebo prompt +@msg must have `kind` alert, confirm, prompt or window musí mít `kind` alert, confirm, prompt nebo window +@msg is a window's answer, whose `value` must be a list of steps je odpověď okna, jejíž `value` musí být seznam kroků +@msg has a step {i} that is not a valid click, change or close má krok {i}, který není platné kliknutí, změna ani zavření @msg must have exactly `kind` and `value` musí mít právě `kind` a `value` @msg name (a toolbar's name) is required name (název panelu nástrojů) je povinné @msg name (a toolbar's name) must be a string name (název panelu nástrojů) musí být řetězec diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..cc03e6ef1b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -233,7 +233,9 @@ liquify-list-end {0}, {1} {0} og {1} @msg is a confirm's answer, whose `value` must be true or false er svaret på en confirm, hvis `value` skal være true eller false @msg is longer than 16 KiB er længere end 16 KiB @msg is a prompt's answer, whose `value` must be a string or null er svaret på en prompt, hvis `value` skal være en streng eller null -@msg must have `kind` alert, confirm or prompt skal have `kind` alert, confirm eller prompt +@msg must have `kind` alert, confirm, prompt or window skal have `kind` alert, confirm, prompt eller window +@msg is a window's answer, whose `value` must be a list of steps er et vindues svar, hvis `value` skal være en liste over trin +@msg has a step {i} that is not a valid click, change or close har et trin {i}, der ikke er et gyldigt klik, en gyldig ændring eller en gyldig lukning @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` er kun til en kørsel uden nogen at spørge: i appen besvarer personen hver dialog @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` skal være et heltal fra 1 til {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` er indlejret mere end 64 niveauer dybt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..e92726501f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8629,7 +8629,9 @@ breakText Glyphs Glyphen @msg missing `picks` `picks` fehlt @msg missing `word` `word` fehlt @msg must be an object with `kind` and `value` muss ein Objekt mit `kind` und `value` sein -@msg must have `kind` alert, confirm or prompt muss `kind` alert, confirm oder prompt haben +@msg must have `kind` alert, confirm, prompt or window muss `kind` alert, confirm, prompt oder window haben +@msg is a window's answer, whose `value` must be a list of steps ist die Antwort auf ein Fenster, deren `value` eine Liste von Schritten sein muss +@msg has a step {i} that is not a valid click, change or close hat einen Schritt {i}, der kein gültiger Klick, keine gültige Änderung und kein gültiges Schließen ist @msg must have exactly `kind` and `value` muss genau `kind` und `value` haben @msg needs a closing quote after the name braucht ein schließendes Anführungszeichen nach dem Namen @msg needs a name braucht einen Namen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..12d3aba3c5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2787,7 +2787,9 @@ liquify-list-end {0}, {1} {0} και {1} @msg is a confirm's answer, whose `value` must be true or false είναι απάντηση σε confirm, οπότε το `value` πρέπει να είναι true ή false @msg is longer than 16 KiB είναι μεγαλύτερο από 16 KiB @msg is a prompt's answer, whose `value` must be a string or null είναι απάντηση σε prompt, οπότε το `value` πρέπει να είναι συμβολοσειρά ή null -@msg must have `kind` alert, confirm or prompt πρέπει να έχει `kind` alert, confirm ή prompt +@msg must have `kind` alert, confirm, prompt or window πρέπει να έχει `kind` alert, confirm, prompt ή window +@msg is a window's answer, whose `value` must be a list of steps είναι απάντηση παραθύρου, της οποίας το `value` πρέπει να είναι λίστα βημάτων +@msg has a step {i} that is not a valid click, change or close έχει ένα βήμα {i} που δεν είναι έγκυρο κλικ, αλλαγή ή κλείσιμο @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog το `answers` είναι μόνο για εκτέλεση χωρίς κανέναν να ερωτηθεί: στην εφαρμογή, το άτομο απαντά σε κάθε παράθυρο διαλόγου @msg `maxFuel` must be a whole number from 1 to {_1} το `maxFuel` πρέπει να είναι ακέραιος από 1 έως {_1} @msg `args{place}` is nested more than 64 levels deep το `args{place}` έχει ένθεση μεγαλύτερη των 64 επιπέδων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..c404d6ed6e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5061,7 +5061,9 @@ liquify-list-end {0}, {1} {0}, {1} @msg is a confirm's answer, whose `value` must be true or false es la respuesta de un confirm, cuyo `value` debe ser true o false @msg is longer than 16 KiB ocupa más de 16 KiB @msg is a prompt's answer, whose `value` must be a string or null es la respuesta de un prompt, cuyo `value` debe ser una cadena o null -@msg must have `kind` alert, confirm or prompt debe tener `kind` alert, confirm o prompt +@msg must have `kind` alert, confirm, prompt or window debe tener `kind` alert, confirm, prompt o window +@msg is a window's answer, whose `value` must be a list of steps es la respuesta de una ventana, cuyo `value` debe ser una lista de pasos +@msg has a step {i} that is not a valid click, change or close tiene un paso {i} que no es un clic, un cambio ni un cierre válido @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` solo es para una ejecución sin nadie a quien preguntar: en la aplicación, la persona responde cada cuadro de diálogo @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` debe ser un número entero de 1 a {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` está anidado a más de 64 niveles diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..2ae421c004 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5302,7 +5302,9 @@ liquify-list-end {0}, {1} {0} ja {1} @msg is a confirm's answer, whose `value` must be true or false on confirm-vastaus, joten sen `value`-arvon on oltava true tai false @msg is longer than 16 KiB on pidempi kuin 16 KiB @msg is a prompt's answer, whose `value` must be a string or null on prompt-vastaus, joten sen `value`-arvon on oltava merkkijono tai null -@msg must have `kind` alert, confirm or prompt `kind`-arvon on oltava alert, confirm tai prompt +@msg must have `kind` alert, confirm, prompt or window `kind`-arvon on oltava alert, confirm, prompt tai window +@msg is a window's answer, whose `value` must be a list of steps on ikkunan vastaus, jonka `value`-arvon on oltava luettelo vaiheista +@msg has a step {i} that is not a valid click, change or close sisältää vaiheen {i}, joka ei ole kelvollinen napsautus, muutos tai sulkeminen @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` on vain ajolle, jossa ei ole ketään kysyttävää: sovelluksessa henkilö vastaa jokaiseen valintaikkunaan @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` on oltava kokonaisluku väliltä 1–{_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` on sisäkkäin yli 64 tason syvyydellä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..aa2a24c90d 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9728,7 +9728,9 @@ breakText Glyphs Glyphes @msg more than {MAX_IMPORT} presets plus de {MAX_IMPORT} paramètres prédéfinis @msg moved must be [[x,y]…] moved doit être [[x,y]…] @msg must be an object with `kind` and `value` doit être un objet avec `kind` et `value` -@msg must have `kind` alert, confirm or prompt doit avoir `kind` alert, confirm ou prompt +@msg must have `kind` alert, confirm, prompt or window doit avoir `kind` alert, confirm, prompt ou window +@msg is a window's answer, whose `value` must be a list of steps est la réponse d’une fenêtre, dont la `value` doit être une liste d’étapes +@msg has a step {i} that is not a valid click, change or close a une étape {i} qui n’est ni un clic, ni une modification, ni une fermeture valide @msg must have exactly `kind` and `value` doit avoir exactement `kind` et `value` @msg name (a toolbar's name) is required name (le nom d’une barre d’outils) est obligatoire @msg name (a toolbar's name) must be a string name (le nom d’une barre d’outils) doit être une chaîne diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..5bdc231564 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7736,7 +7736,9 @@ liquify-list-end {0}, {1} {0} और {1} @msg is a confirm's answer, whose `value` must be true or false यह confirm का उत्तर है, इसलिए इसका `value` true या false होना चाहिए @msg is longer than 16 KiB 16 KiB से लंबा है @msg is a prompt's answer, whose `value` must be a string or null यह prompt का उत्तर है, इसलिए इसका `value` स्ट्रिंग या null होना चाहिए -@msg must have `kind` alert, confirm or prompt `kind` alert, confirm या prompt होना चाहिए +@msg must have `kind` alert, confirm, prompt or window `kind` alert, confirm, prompt या window होना चाहिए +@msg is a window's answer, whose `value` must be a list of steps एक window का उत्तर है, जिसका `value` चरणों की सूची होना चाहिए +@msg has a step {i} that is not a valid click, change or close में चरण {i} मान्य क्लिक, बदलाव या बंद करना नहीं है @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` केवल ऐसे रन के लिए है जिसमें पूछने के लिए कोई नहीं है: ऐप में, व्यक्ति हर डायलॉग का उत्तर देता है @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 1 से {_1} तक की पूर्ण संख्या होनी चाहिए @msg `args{place}` is nested more than 64 levels deep `args{place}` 64 से अधिक स्तर गहराई तक नेस्ट किया गया है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..af96effe62 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9739,7 +9739,9 @@ breakText Glyphs Glifák @msg more than {MAX_IMPORT} presets több mint {MAX_IMPORT} előbeállítás @msg moved must be [[x,y]…] moved: [[x,y]…] kell @msg must be an object with `kind` and `value` `kind` és `value` kulcsot tartalmazó objektum kell -@msg must have `kind` alert, confirm or prompt a `kind` értéke alert, confirm vagy prompt kell legyen +@msg must have `kind` alert, confirm, prompt or window a `kind` értéke alert, confirm, prompt vagy window kell legyen +@msg is a window's answer, whose `value` must be a list of steps egy ablak válasza, amelynek `value` értéke lépések listája kell legyen +@msg has a step {i} that is not a valid click, change or close {i}. lépése nem érvényes kattintás, módosítás vagy bezárás @msg must have exactly `kind` and `value` pontosan a `kind` és a `value` kulcsot kell tartalmaznia @msg name (a toolbar's name) is required name (egy eszköztár neve): kötelező @msg name (a toolbar's name) must be a string name (egy eszköztár neve): karakterlánc kell diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..87d73912db 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -140,7 +140,9 @@ @msg is a confirm's answer, whose `value` must be true or false adalah jawaban confirm, yang `value`-nya harus true atau false @msg is longer than 16 KiB lebih panjang dari 16 KiB @msg is a prompt's answer, whose `value` must be a string or null adalah jawaban prompt, yang `value`-nya harus berupa string atau null -@msg must have `kind` alert, confirm or prompt harus memiliki `kind` alert, confirm, atau prompt +@msg must have `kind` alert, confirm, prompt or window harus memiliki `kind` alert, confirm, prompt, atau window +@msg is a window's answer, whose `value` must be a list of steps adalah jawaban jendela, yang `value`-nya harus berupa daftar langkah +@msg has a step {i} that is not a valid click, change or close memiliki langkah {i} yang bukan klik, perubahan, atau penutupan yang valid @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` hanya untuk proses tanpa orang yang dapat ditanya: di aplikasi, pengguna menjawab setiap dialog @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` harus berupa bilangan bulat dari 1 sampai {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` bersarang lebih dari 64 tingkat diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..5aab7c3e3d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8678,7 +8678,9 @@ breakText Glyphs Glifi @msg missing `picks` `picks` mancante @msg missing `word` `word` mancante @msg must be an object with `kind` and `value` deve essere un oggetto con `kind` e `value` -@msg must have `kind` alert, confirm or prompt deve avere `kind` alert, confirm o prompt +@msg must have `kind` alert, confirm, prompt or window deve avere `kind` alert, confirm, prompt o window +@msg is a window's answer, whose `value` must be a list of steps è la risposta di una finestra, il cui `value` deve essere un elenco di passaggi +@msg has a step {i} that is not a valid click, change or close ha un passaggio {i} che non è un clic, una modifica o una chiusura validi @msg must have exactly `kind` and `value` deve avere esattamente `kind` e `value` @msg needs a closing quote after the name richiede una virgoletta di chiusura dopo il nome @msg needs a name richiede un nome diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..ef0740a8bb 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7495,7 +7495,9 @@ axis Y Axis Y 軸 @msg missing `picks` `picks` がありません @msg missing `word` `word` がありません @msg must be an object with `kind` and `value` には `kind` と `value` を持つオブジェクトを指定してください -@msg must have `kind` alert, confirm or prompt の `kind` には alert、confirm、prompt のいずれかを指定してください +@msg must have `kind` alert, confirm, prompt or window の `kind` には alert、confirm、prompt、window のいずれかを指定してください +@msg is a window's answer, whose `value` must be a list of steps は window の回答で、`value` には手順のリストを指定してください +@msg has a step {i} that is not a valid click, change or close の手順 {i} は有効なクリック、変更、閉じる操作のいずれでもありません @msg must have exactly `kind` and `value` には `kind` と `value` だけを指定してください @msg needs a closing quote after the name 名前の後に閉じ引用符が必要です @msg needs a name 名前が必要です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..e7223c60c8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1085,7 +1085,9 @@ @msg more than {MAX_IMPORT} presets {MAX_IMPORT}-ზე მეტი პრესეტი @msg moved must be [[x,y]…] moved უნდა იყოს [[x,y]…] @msg must be an object with `kind` and `value` უნდა იყოს ობიექტი `kind`-ით და `value`-თი -@msg must have `kind` alert, confirm or prompt `kind` უნდა იყოს alert, confirm ან prompt +@msg must have `kind` alert, confirm, prompt or window `kind` უნდა იყოს alert, confirm, prompt ან window +@msg is a window's answer, whose `value` must be a list of steps არის ფანჯრის პასუხი, რომლის `value` უნდა იყოს ნაბიჯების სია +@msg has a step {i} that is not a valid click, change or close შეიცავს ნაბიჯს {i}, რომელიც არ არის სწორი დაწკაპუნება, ცვლილება ან დახურვა @msg must have exactly `kind` and `value` უნდა ჰქონდეს ზუსტად `kind` და `value` @msg name (a toolbar's name) is required საჭიროა name (ხელსაწყოთა ზოლის სახელი) @msg name (a toolbar's name) must be a string name (ხელსაწყოთა ზოლის სახელი) უნდა იყოს სტრიქონი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..e40e7055a2 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -9508,7 +9508,9 @@ breakText Glyphs 글리프 @msg more than {MAX_IMPORT} presets 사전 설정이 {MAX_IMPORT}개보다 많습니다 @msg moved must be [[x,y]…] moved는 [[x,y]…]여야 합니다 @msg must be an object with `kind` and `value` `kind`와 `value`가 있는 개체여야 합니다 -@msg must have `kind` alert, confirm or prompt `kind`가 alert, confirm 또는 prompt여야 합니다 +@msg must have `kind` alert, confirm, prompt or window `kind`가 alert, confirm, prompt 또는 window여야 합니다 +@msg is a window's answer, whose `value` must be a list of steps 창의 답이며, `value`는 단계 목록이어야 합니다 +@msg has a step {i} that is not a valid click, change or close 단계 {i}이(가) 올바른 클릭, 변경 또는 닫기가 아닙니다 @msg must have exactly `kind` and `value` `kind`와 `value`만 있어야 합니다 @msg name (a toolbar's name) is required name(도구 막대 이름)이 필요합니다 @msg name (a toolbar's name) must be a string name(도구 막대 이름)은 문자열이어야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..d52992f4a9 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -7380,7 +7380,9 @@ imageTrace Outline Contour @msg more than {MAX_IMPORT} presets meer dan {MAX_IMPORT} voorinstellingen @msg moved must be [[x,y]…] moved moet [[x,y]…] zijn @msg must be an object with `kind` and `value` moet een object met `kind` en `value` zijn -@msg must have `kind` alert, confirm or prompt moet `kind` alert, confirm of prompt hebben +@msg must have `kind` alert, confirm, prompt or window moet `kind` alert, confirm, prompt of window hebben +@msg is a window's answer, whose `value` must be a list of steps is het antwoord van een venster, waarvan `value` een lijst met stappen moet zijn +@msg has a step {i} that is not a valid click, change or close heeft een stap {i} die geen geldige klik, wijziging of sluiting is @msg must have exactly `kind` and `value` moet precies `kind` en `value` hebben @msg name (a toolbar's name) is required name (de naam van een werkbalk) is vereist @msg name (a toolbar's name) must be a string name (de naam van een werkbalk) moet een string zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..1a2148f0e1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8882,7 +8882,9 @@ breakText Glyphs Glify @msg missing `picks` brak `picks` @msg missing `word` brak `word` @msg must be an object with `kind` and `value` musi być obiektem z `kind` i `value` -@msg must have `kind` alert, confirm or prompt `kind` musi mieć wartość alert, confirm lub prompt +@msg must have `kind` alert, confirm, prompt or window `kind` musi mieć wartość alert, confirm, prompt lub window +@msg is a window's answer, whose `value` must be a list of steps jest odpowiedzią okna, której `value` musi być listą kroków +@msg has a step {i} that is not a valid click, change or close ma krok {i}, który nie jest prawidłowym kliknięciem, zmianą ani zamknięciem @msg must have exactly `kind` and `value` musi mieć dokładnie `kind` i `value` @msg needs a closing quote after the name wymaga zamykającego cudzysłowu po nazwie @msg needs a name wymaga nazwy diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..82cdb0a2b2 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9930,7 +9930,9 @@ swatch Yellow Green Verde-amarelado @msg more than {MAX_IMPORT} presets mais de {MAX_IMPORT} predefinições @msg moved must be [[x,y]…] moved deve ser [[x,y]…] @msg must be an object with `kind` and `value` deve ser um objeto com `kind` e `value` -@msg must have `kind` alert, confirm or prompt deve ter `kind` alert, confirm ou prompt +@msg must have `kind` alert, confirm, prompt or window deve ter `kind` alert, confirm, prompt ou window +@msg is a window's answer, whose `value` must be a list of steps é a resposta de uma janela, cujo `value` deve ser uma lista de etapas +@msg has a step {i} that is not a valid click, change or close tem uma etapa {i} que não é um clique, uma alteração nem um fechamento válido @msg must have exactly `kind` and `value` deve ter exatamente `kind` e `value` @msg name (a toolbar's name) is required name (o nome de uma barra de ferramentas) é obrigatório @msg name (a toolbar's name) must be a string name (o nome de uma barra de ferramentas) deve ser uma string diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..6f351f1d76 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5083,7 +5083,9 @@ liquify-list-end {0}, {1} {0} и {1} @msg is a confirm's answer, whose `value` must be true or false является ответом на confirm, поэтому его `value` должно быть true или false @msg is longer than 16 KiB длиннее 16 КиБ @msg is a prompt's answer, whose `value` must be a string or null является ответом на prompt, поэтому его `value` должно быть строкой или null -@msg must have `kind` alert, confirm or prompt должен иметь `kind` alert, confirm или prompt +@msg must have `kind` alert, confirm, prompt or window должен иметь `kind` alert, confirm, prompt или window +@msg is a window's answer, whose `value` must be a list of steps является ответом окна, `value` которого должен быть списком шагов +@msg has a step {i} that is not a valid click, change or close содержит шаг {i}, который не является допустимым щелчком, изменением или закрытием @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` предназначен только для запуска, в котором некого спросить: в приложении человек сам отвечает на каждое диалоговое окно @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` должен быть целым числом от 1 до {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` вложен глубже 64 уровней diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..532e1ade50 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4959,7 +4959,9 @@ liquify-list-end {0}, {1} {0} och {1} @msg is a confirm's answer, whose `value` must be true or false är svaret på en confirm, vars `value` måste vara true eller false @msg is longer than 16 KiB är längre än 16 KiB @msg is a prompt's answer, whose `value` must be a string or null är svaret på en prompt, vars `value` måste vara en sträng eller null -@msg must have `kind` alert, confirm or prompt måste ha `kind` alert, confirm eller prompt +@msg must have `kind` alert, confirm, prompt or window måste ha `kind` alert, confirm, prompt eller window +@msg is a window's answer, whose `value` must be a list of steps är ett fönsters svar, vars `value` måste vara en lista med steg +@msg has a step {i} that is not a valid click, change or close har ett steg {i} som inte är ett giltigt klick, en giltig ändring eller en giltig stängning @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` är bara för en körning utan någon att fråga: i appen svarar personen på varje dialogruta @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` måste vara ett heltal från 1 till {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` är kapslat mer än 64 nivåer djupt diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..daba147a6d 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -5774,12 +5774,14 @@ fn script_answers_errors_are_translated() { "is a confirm's answer, whose `value` must be true or false", "is longer than 16 KiB", "is a prompt's answer, whose `value` must be a string or null", - "must have `kind` alert, confirm or prompt", + "must have `kind` alert, confirm, prompt or window", + "is a window's answer, whose `value` must be a list of steps", ]; let in_app = "`answers` is only for a run with nobody to ask: in the app, the person answers each dialog"; let lists = ["`answers` must be a list of answers", "`answers` has more than {MAX_ANSWERS} answers", "`answers` is larger than 1 MiB"]; + let step = "has a step {i} that is not a valid click, change or close"; let scanned = message_literals(); - for template in reasons.into_iter().chain(lists).chain(["`answers[{i}]` {e}", in_app]) { + for template in reasons.into_iter().chain(lists).chain(["`answers[{i}]` {e}", in_app, step]) { assert!(scanned.contains(template), "{template}"); } let ok = json!({"kind": "alert", "value": "ok"}); @@ -5791,6 +5793,7 @@ fn script_answers_errors_are_translated() { json!({"kind": "prompt", "value": "x".repeat(16 * 1024 + 1)}), json!({"kind": "prompt", "value": 1}), json!({"kind": "beep", "value": 1}), + json!({"kind": "window", "value": "click"}), ]; let run = |s: &mut Session, answers: Value| s.execute("script.run", &json!({"source": "1", "answers": answers})).unwrap_err(); let mut s = Session::new(); @@ -5807,6 +5810,8 @@ fn script_answers_errors_are_translated() { errors.push((run(&mut s, json!(vec![ok.clone(); 10_001])), "`answers` has more than 10000 answers".to_string(), None)); let long = json!({"kind": "prompt", "value": "x".repeat(16 * 1024)}); errors.push((run(&mut s, json!(vec![long; 70])), lists[2].to_string(), None)); + let steps = json!([{"kind": "window", "value": [{"event": "close"}, {"event": "tap"}]}]); + errors.push((run(&mut s, steps), "`answers[0]` has a step 1 that is not a valid click, change or close".to_string(), None)); s.script_frames = true; errors.push((run(&mut s, json!([ok])), in_app.to_string(), None)); for (e, want, reason) in &errors { @@ -5826,8 +5831,8 @@ fn script_answers_errors_are_translated() { let numbers: Vec<&str> = want.split(|c: char| !c.is_ascii_digit()).filter(|n| !n.is_empty()).collect(); let names = ["`answers", "`kind`", "`value`", "true", "false", "null"]; assert!(numbers.iter().chain(&names).all(|n| !want.contains(n) || shown.contains(n)), "{code}: {shown}"); - if want.ends_with("alert, confirm or prompt") { - assert!(["alert", "confirm", "prompt"].iter().all(|k| shown.contains(k)), "{code}: {shown}"); + if want.ends_with("alert, confirm, prompt or window") { + assert!(["alert", "confirm", "prompt", "window"].iter().all(|k| shown.contains(k)), "{code}: {shown}"); } } } diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..22568734be 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7871,7 +7871,9 @@ axis Y Axis Y ekseni @msg missing `picks` `picks` eksik @msg missing `word` `word` eksik @msg must be an object with `kind` and `value` `kind` ve `value` içeren bir nesne olmalıdır -@msg must have `kind` alert, confirm or prompt `kind` değeri alert, confirm veya prompt olmalıdır +@msg must have `kind` alert, confirm, prompt or window `kind` değeri alert, confirm, prompt veya window olmalıdır +@msg is a window's answer, whose `value` must be a list of steps bir pencerenin yanıtıdır ve `value` değeri bir adım listesi olmalıdır +@msg has a step {i} that is not a valid click, change or close içindeki {i}. adım geçerli bir tıklama, değişiklik veya kapatma değil @msg must have exactly `kind` and `value` yalnızca `kind` ve `value` içermelidir @msg needs a closing quote after the name addan sonra bir kapanış tırnağı gerekir @msg needs a name bir ad gerekir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..1c44123d26 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9509,7 +9509,9 @@ breakText Glyphs Гліфи @msg more than {MAX_IMPORT} presets понад {MAX_IMPORT} наборів @msg moved must be [[x,y]…] moved має бути [[x,y]…] @msg must be an object with `kind` and `value` має бути об’єктом із `kind` і `value` -@msg must have `kind` alert, confirm or prompt повинен мати `kind` зі значенням alert, confirm або prompt +@msg must have `kind` alert, confirm, prompt or window повинен мати `kind` зі значенням alert, confirm, prompt або window +@msg is a window's answer, whose `value` must be a list of steps є відповіддю вікна, `value` якої має бути списком кроків +@msg has a step {i} that is not a valid click, change or close має крок {i}, який не є допустимим клацанням, зміною або закриттям @msg must have exactly `kind` and `value` повинен мати рівно `kind` і `value` @msg name (a toolbar's name) is required name (ім’я панелі інструментів) є обов’язковим @msg name (a toolbar's name) must be a string name (ім’я панелі інструментів) має бути рядком diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..2758865931 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5582,7 +5582,9 @@ liquify-list-end {0}, {1} {0} và {1} @msg is a confirm's answer, whose `value` must be true or false là câu trả lời cho confirm, nên `value` phải là true hoặc false @msg is longer than 16 KiB dài hơn 16 KiB @msg is a prompt's answer, whose `value` must be a string or null là câu trả lời cho prompt, nên `value` phải là chuỗi hoặc null -@msg must have `kind` alert, confirm or prompt phải có `kind` là alert, confirm hoặc prompt +@msg must have `kind` alert, confirm, prompt or window phải có `kind` là alert, confirm, prompt hoặc window +@msg is a window's answer, whose `value` must be a list of steps là câu trả lời của một cửa sổ, có `value` phải là danh sách các bước +@msg has a step {i} that is not a valid click, change or close có bước {i} không phải là một lần nhấp, thay đổi hoặc đóng hợp lệ @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` chỉ dành cho lần chạy không có ai để hỏi: trong ứng dụng, người dùng trả lời từng hộp thoại @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` phải là số nguyên từ 1 đến {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` lồng sâu hơn 64 cấp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..dac4499a58 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8888,7 +8888,9 @@ breakText Glyphs 字形 @msg missing `picks` 缺少 `picks` @msg missing `word` 缺少 `word` @msg must be an object with `kind` and `value` 必须是包含 `kind` 和 `value` 的对象 -@msg must have `kind` alert, confirm or prompt `kind` 必须是 alert、confirm 或 prompt +@msg must have `kind` alert, confirm, prompt or window `kind` 必须是 alert、confirm、prompt 或 window +@msg is a window's answer, whose `value` must be a list of steps 是窗口的回答,其 `value` 必须是步骤列表 +@msg has a step {i} that is not a valid click, change or close 的第 {i} 步不是有效的点击、更改或关闭 @msg must have exactly `kind` and `value` 必须只包含 `kind` 和 `value` @msg needs a closing quote after the name 名称后需要右引号 @msg needs a name 需要名称 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..bf6ee14a81 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8824,7 +8824,9 @@ breakText Glyphs 字符 @msg missing `picks` 未提供 `picks` @msg missing `word` 未提供 `word` @msg must be an object with `kind` and `value` 必須是包含 `kind` 和 `value` 的物件 -@msg must have `kind` alert, confirm or prompt `kind` 必須是 alert、confirm 或 prompt +@msg must have `kind` alert, confirm, prompt or window `kind` 必須是 alert、confirm、prompt 或 window +@msg is a window's answer, whose `value` must be a list of steps 是視窗的回答,其 `value` 必須是步驟清單 +@msg has a step {i} that is not a valid click, change or close 的第 {i} 步不是有效的點按、變更或關閉 @msg must have exactly `kind` and `value` 只能有 `kind` 和 `value` @msg needs a closing quote after the name 名稱之後需要結尾引號 @msg needs a name 需要名稱 diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 7bc52f35b1..f3d5f14912 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -1,12 +1,13 @@ //! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with -//! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer. +//! `alert`, `confirm`, `prompt`, a ScriptUI dialog's `show()` or a `File` or `Folder` file dialog, +//! waits for the person's answer. use serde_json::json; use crate::VectorcraftApp; -use crate::dialogs::script_run; +use crate::dialogs::{script_run, script_window}; use crate::state::Dialog; /// Advances the running script by one slice, or asks what its growth needs asked. @@ -29,7 +30,7 @@ pub fn poll(app: &mut VectorcraftApp) { if cursor_settings != (app.session.caps_lock, app.session.prefs.use_precise_cursors) { app.canvas.hover_cursor = None; } - if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::GROWTH_KIND) { + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::GROWTH_KIND || d.kind == script_window::KIND) { app.ui.dialog = None; } script_run::settle_close(app); @@ -49,6 +50,14 @@ pub fn poll(app: &mut VectorcraftApp) { /// question about its growth. Closes the script's dialog when the run no longer waits at it. /// → true while the run waits. fn ask(app: &mut VectorcraftApp) -> bool { + // A ScriptUI dialog the script closed gives way to the file dialog or dialog function it waits + // at now. + if app.session.script_window().is_none() + && (app.session.script_picker().is_some() || app.session.script_dialog().is_some()) + && app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND) + { + app.ui.dialog = None; + } if let Some(picker) = app.session.script_picker() { if app.ui.dialog.is_none() { script_run::open_picker(app, &picker); @@ -68,6 +77,21 @@ fn ask(app: &mut VectorcraftApp) -> bool { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::NOTICE_KIND) { app.ui.dialog = None; } + if let Some(window) = app.session.script_window() { + // A dialog the script showed after closing the one that is open replaces it. + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND && !script_window::is_open_for(d, &window)) { + app.ui.dialog = None; + } + if app.ui.dialog.is_none() { + script_window::open(app, &window); + } + return true; + } + // While a handler runs, the ScriptUI dialog stays open, until the run ends or asks about its + // growth. + if app.session.script_waiting() && app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND) { + app.ui.dialog = None; + } if app.session.script_waiting() { if app.ui.dialog.is_none() { app.ui.dialog = Some(Dialog::new(script_run::GROWTH_KIND, json!({}))); diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index e0619ddaf7..ac934f6d18 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -43,6 +43,7 @@ mod screenshots; mod script_check; mod script_dialogs; mod script_run; +mod script_window; mod scripts_menu; mod scrub; mod selectall; diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs new file mode 100644 index 0000000000..1cc241b049 --- /dev/null +++ b/crates/ui-egui/src/tests/script_window.rs @@ -0,0 +1,273 @@ +//! A script's ScriptUI dialog in the app: it opens when `show()` waits, takes clicks and changes +//! from the person and from `ui.dialog.confirm`, Enter and Escape, Stop, and quitting while it +//! waits. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_engine::script::{UiEvent, UiValue}; + +use crate::dialogs::script_run::CLOSE_KIND; +use crate::dialogs::script_window::{self, KIND}; +use crate::{VectorcraftApp, dialogs, menus, script_runs}; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + app +} + +fn objects(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +const DRAW: &str = "vc.run('shape.rectangle', {x:0,y:0,width:10,height:10});"; + +const FORM: &str = "var w = new Window('dialog', 'Make'); var name = w.add('edittext', undefined, 'first', {name: 'name'}); \ + var bold = w.add('checkbox', undefined, 'Bold'); bold.onClick = function () { name.text = 'clicked'; }; \ + w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel');"; + +fn start(app: &mut VectorcraftApp, source: &str) { + menus::run_ui_command(app, "ui.runScript", &json!({"source": source, "name": "w.js"})).unwrap().unwrap(); +} + +/// Polls the run until it ends, or until its ScriptUI dialog is open and it waits (true). +fn until_window(app: &mut VectorcraftApp) -> bool { + for _ in 0..10_000 { + if !app.session.script_running() { + return false; + } + script_runs::poll(app); + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND) && app.session.script_window().is_some() { + return true; + } + } + panic!("the script neither ended nor opened its dialog"); +} + +/// Gives the dialog an event as `ui.dialog.set` and `ui.dialog.confirm` do. +fn give(app: &mut VectorcraftApp, event: Value) -> Result { + let d = app.ui.dialog.as_mut().unwrap(); + for (k, v) in event.as_object().unwrap() { + d.fields.insert(k.clone(), v.clone()); + } + dialogs::confirm(app) +} + +thread_local! { + static CTX: egui::Context = { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx + }; +} + +/// One headless frame of the dialog layer and the shortcuts. Each key pressed in it is let go in a +/// second frame. +fn frame(app: &mut VectorcraftApp, events: Vec) { + let ctx = CTX.with(Clone::clone); + let released: Vec = events + .iter() + .filter_map(|e| match e { + egui::Event::Key { key, physical_key, modifiers, pressed: true, .. } => { + Some(egui::Event::Key { key: *key, physical_key: *physical_key, pressed: false, repeat: false, modifiers: *modifiers }) + } + _ => None, + }) + .collect(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let pressed = !released.is_empty(); + for events in std::iter::once(events).chain(pressed.then_some(released)) { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect, ..Default::default() }, |ui| { + crate::shortcuts::handle(app, ui.ctx()); + dialogs::show(app, ui.ctx()); + }); + out.textures_delta.clear(); + } +} + +fn key(k: egui::Key) -> egui::Event { + egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() } +} + +fn log(app: &VectorcraftApp) -> Value { + app.session.script_report().unwrap()["log"].clone() +} + +#[test] +fn the_dialog_takes_events_and_stays_open_while_its_handlers_run() { + let mut app = app(); + start(&mut app, &format!("{DRAW} {FORM} var r = w.show(); vc.log([r, name.text, bold.value]);")); + assert!(until_window(&mut app)); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("title"), "Make"); + frame(&mut app, Vec::new()); + give(&mut app, json!({"event": "click", "control": "Bold"})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the dialog stays open for the next wait"); + assert!(until_window(&mut app)); + assert_eq!(app.session.script_window().unwrap().nodes[1].text, "clicked", "the handler changed the field"); + assert!(give(&mut app, json!({"event": "click", "control": 99})).is_err()); + assert!(give(&mut app, json!({"event": "wave"})).is_err()); + give(&mut app, json!({"event": "change", "control": "name", "value": "Ann"})).unwrap(); + assert!(until_window(&mut app)); + frame(&mut app, vec![key(egui::Key::Enter)]); + assert!(!until_window(&mut app), "Enter clicks OK, which closes the dialog"); + assert_eq!(log(&app), json!([[1, "Ann", true]])); + assert!(app.ui.dialog.is_none()); + assert_eq!(objects(&app), 1); +} + +#[test] +fn text_still_in_a_field_reaches_the_script_before_a_click() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log([w.show(), name.text]);")); + assert!(until_window(&mut app)); + let w = app.session.script_window().unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("text1".into(), json!("Ann")); + let mut events = vec![UiEvent::Click(3)]; + script_window::commit_drafts(&w, d, &mut events); + assert_eq!(events, vec![UiEvent::Change(1, UiValue::Text("Ann".into())), UiEvent::Click(3)]); + assert!(!d.fields.contains_key("text1"), "the text is given once"); + d.fields.insert("queued".into(), json!([{"event": "change", "control": 1, "value": "Ann"}, {"event": "click", "control": 3, "value": null}])); + frame(&mut app, Vec::new()); + assert!(until_window(&mut app), "the script takes the change and waits again"); + frame(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([[1, "Ann"]])); +} + +#[test] +fn escape_clicks_the_cancel_button_and_closes_a_dialog_without_one() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + frame(&mut app, vec![key(egui::Key::Escape)]); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([2])); + start(&mut app, "var w = new Window('dialog'); w.add('statictext', undefined, 'Hi'); vc.log(w.show());"); + assert!(until_window(&mut app)); + dialogs::cancel(&mut app); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([0])); +} + +#[test] +fn escape_keeps_the_dialog_open_until_the_script_closes_it() { + let mut app = app(); + start(&mut app, "var w = new Window('dialog'); w.add('edittext', undefined, 'a'); w.onClose = function () { return false; }; vc.log(w.show());"); + assert!(until_window(&mut app)); + start_typing(&mut app); + dialogs::cancel(&mut app); + let d = app.ui.dialog.as_ref().expect("the dialog stays open"); + assert_eq!(d.fields["queued"], json!([{"event": "close", "control": null, "value": null}]), "with the close after the typed text"); + assert!(until_window(&mut app), "the script takes the text and waits again"); + assert_eq!(app.session.script_window().unwrap().nodes[1].text, "typed"); + frame(&mut app, Vec::new()); + assert!(until_window(&mut app), "onClose kept the dialog open"); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("queued")); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +fn start_typing(app: &mut VectorcraftApp) { + app.ui.dialog.as_mut().unwrap().fields.insert("text1".into(), json!("typed")); +} + +#[test] +fn escape_gives_the_typed_text_before_the_cancel_click() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var e = w.add('edittext', undefined, 'old'); var c = w.add('button', undefined, 'Cancel'); \ + c.onClick = function () { vc.log(e.text); w.close(2); }; vc.log(w.show());", + ); + assert!(until_window(&mut app)); + start_typing(&mut app); + dialogs::cancel(&mut app); + assert!(until_window(&mut app), "the script takes the text and waits again"); + frame(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on Cancel closes the dialog"); + assert_eq!(log(&app), json!(["typed", 2])); +} + +#[test] +fn a_second_dialog_replaces_the_first() { + let mut app = app(); + start( + &mut app, + "var a = new Window('dialog', 'A'); a.add('edittext', undefined, 'x'); a.add('button', undefined, 'OK'); a.show(); \ + var b = new Window('dialog', 'B'); b.add('edittext', undefined, 'y'); b.add('button', undefined, 'OK'); vc.log([b.show(), b.children[0].text]);", + ); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("text1".into(), json!("left over")); + assert!(until_window(&mut app)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.str("title"), "B", "the second dialog's title"); + assert!(!d.fields.contains_key("text1"), "without the first dialog's typed text"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, "y"]])); +} + +#[test] +fn a_dialog_function_after_show_opens_its_own_dialog() { + let mut app = app(); + start(&mut app, &format!("{FORM} w.show(); alert('done');")); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + for _ in 0..100 { + script_runs::poll(&mut app); + if app.ui.dialog.as_ref().is_some_and(|d| d.kind != KIND) { + break; + } + } + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::script_run::NOTICE_KIND), "the alert opens"); + assert!(app.session.script_dialog().is_some()); +} + +#[test] +fn stop_in_the_dialog_rolls_the_run_back() { + let mut app = app(); + start(&mut app, &format!("{DRAW} {FORM} w.show(); vc.log('after');")); + assert!(until_window(&mut app)); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); + assert_eq!(objects(&app), 0); + assert_eq!(app.session.script_report().unwrap()["dialogs"][0]["answer"], "stop"); + assert!(app.ui.dialog.is_none()); +} + +#[test] +fn quitting_while_the_dialog_waits_asks_and_cancel_shows_it_again() { + let mut app = app(); + start(&mut app, &format!("{DRAW} {FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + app.ui.dialog.as_mut().unwrap().fields.insert("text1".into(), json!("typed")); + dialogs::script_run::ask_to_close(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(CLOSE_KIND)); + dialogs::cancel(&mut app); + assert!(until_window(&mut app), "the dialog opens again"); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("text1"), "typed", "with the text typed in its field"); + dialogs::script_run::ask_to_close(&mut app); + dialogs::confirm(&mut app).unwrap(); + assert!(!app.session.script_running()); + assert_eq!(objects(&app), 0); +} + +#[test] +fn a_large_dialog_draws_in_a_small_window() { + let mut app = app(); + let source = "var w = new Window('dialog', 'Big'); var p = w.add('panel', undefined, 'Lots'); \ + for (var i = 0; i < 200; i++) p.add('checkbox', undefined, 'Option ' + i); \ + var l = w.add('listbox', undefined, ['a', 'b']); var d = w.add('dropdownlist', undefined, ['x', 'y']); \ + w.add('slider', undefined, 2, 0, 5); w.add('progressbar', undefined, 1, 4); w.add('edittext', undefined, 'm', {multiline: true}); \ + w.add('button', undefined, 'OK'); vc.log(w.show());"; + start(&mut app, source); + assert!(until_window(&mut app)); + frame(&mut app, Vec::new()); + frame(&mut app, Vec::new()); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([1])); +} diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..771273aed2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2841,10 +2841,12 @@ app's own errors, syntax errors and limits. The status bar shows a `script` mess - `console` is `{lines, droppedLines, truncatedLines}`: the run's own output, `vc.log` lines and uncaught error, as text. - `dialogs` lists the run's dialogs in the order they opened, as `{kind, message, title, errorIcon, answer}` for - `alert`, `{kind, message, title, noAsDefault, answer}` for `confirm` and `{kind, message, title, preset, answer}` - for `prompt`. `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, `"stop"` for a dialog the - run ended at, or `"missing"` for a dialog `answers` had no answer for. `dialogCount` counts every dialog, and - `dialogsTruncated` is true when the list stopped at its limit. + `alert`, `{kind, message, title, noAsDefault, answer}` for `confirm`, `{kind, message, title, preset, answer}` + for `prompt` and `{kind, title, controls, events, answer}` for a ScriptUI dialog's `show()` (kind `window`). + `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, the number `show()` returned, `"stop"` + for a dialog the run ended at, `"missing"` for a dialog `answers` had no answer or no step for, or `"error"` for a + `show()` that ended with an error. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list + stopped at its limit. ```json {"name":"run_command","arguments":{"command":"script.run","params":{"source":"vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"}}} @@ -2895,6 +2897,67 @@ empty object are the same. vectorcraft-cli run --cmd script.run --params '{"source": "if (confirm(\"Add a frame?\")) vc.log(prompt(\"Name\", \"Frame\"));", "answers": [{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "Border"}]}' ``` +The help pages https://extendscript.docsforadobe.dev/user-interface-tools/window-object/, +https://extendscript.docsforadobe.dev/user-interface-tools/control-objects/ and +https://extendscript.docsforadobe.dev/user-interface-tools/types-of-controls/ describe ScriptUI's `Window` and its +controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and shows it: + +- `new Window("dialog"[, title, bounds, properties])` makes a dialog. Another type (`palette`, `window`) or a + resource string throws an `Error` that says it is not available yet. +- `container.add(type[, bounds, ...])` adds a control to the dialog, a `group` or a `panel` and returns it. The + types are `group`, `panel`, `statictext`, `edittext`, `button`, `checkbox`, `radiobutton`, `dropdownlist`, + `listbox`, `slider` and `progressbar`. After `bounds`, a text control takes its text and `properties` (`name`, + and `multiline` and `readonly` for `edittext`), a list takes an array of item texts, a `slider` takes its value, + minimum and maximum (0 and 100 when left out), and a `progressbar` its value and maximum. A `listbox` with + `multiselect` and the other control types (`tabbedpanel`, `tab`, `scrollbar`, `image`, `iconbutton`, `treeview` + and the rest) throw that they are not available yet, and an unknown type throws too. +- A list's `add("item", text)` adds an item, `removeAll()` removes them, `items` lists them and `selection` is the + selected item or `null`; setting it to an item or an index selects it. An item has `text`, `index` and + `selected`. +- A control has `text`, `value`, `enabled`, `visible`, `name`, `bounds`, `preferredSize`, `alignment`, `parent`, + `window`, `show()` and `hide()`. A container also has `children`, `orientation` (`row`, `column` or `stack`; a + group starts as a row and the dialog and a panel as a column), `alignChildren`, `spacing` (10 to start), `margins` + (15 to start, 0 for a group) and `findElement(name)`. The dialog has `defaultElement`, `cancelElement`, + `close([result])` and `hide()`. `center()`, `layout.layout()` and `layout.resize()` do nothing. + +`show()` opens the dialog, runs `onShow`, and waits for the person. A click runs the control's `onClick`; a check +box turns its value over first, and a radio button turns on and the other radio buttons in its container off. An +edit field gives its text when it loses the keyboard focus, at Enter in a one-line field, or before a click on another +control, and a slider gives its +value when it is let go: each runs `onChanging` and then `onChange`. A list's new selection runs `onChange`. +Handlers run in the run's instructions, and a handler that does not end stops the run at its limit. `show()` +returns the number given to `close(result)` (0 when left out), 1 when the default button is clicked and 2 when the +cancel button is clicked, while they have no `onClick`, and 0 for the close box. `onClose` runs before the dialog +closes, and returning `false` keeps it open. The default button is `defaultElement`, else a button named or titled +OK, and the cancel button is `cancelElement`, else a button named or titled Cancel, in any case. A `show()` inside +a handler, or of a dialog that is showing, throws an `Error`, and so does one inside a callback of a built-in +function. A shown dialog can be shown again after it closes. + +`show()` checks the dialog: at most 512 controls, nested at most 16 deep, 1,024 list items in all and 16 KiB of +text a control, past which it throws a `RangeError`, a size or a place that is not a finite number, which throws +too, and a slider's minimum above its maximum. It lays the controls out from each container's `orientation`, +`alignChildren`, `spacing` and `margins` and each control's `alignment`, `preferredSize` and `bounds`, which places +it in its container. Sizes and places are kept within 8,192 pixels. These limits are VectorCraft's own. + +In the app, the dialog (kind `scriptWindow`) draws the controls where they were laid out and has a Stop button, +which ends the run as `script.stop` does. Enter outside a field clicks the default button. Escape clicks the +cancel button, or closes the dialog when it has none. Quitting while it waits asks whether to stop the script, and +Cancel shows it again. `ui.dialog.set` with `event` (`click`, `change` or `close`), `control` (a control's index in +the dialog, its name or its text) and `value`, then `ui.dialog.confirm`, gives the script that event; a disabled or +hidden control, a value out of a list's range and a click on a control that takes none are errors, and the dialog +stays open. + +A run with nobody to ask takes `{kind: "window", value: [step, ...]}` from `answers` for each `show()`. A step is +`{control, event: "click"}`, `{control, event: "change", value}` or `{event: "close"}`, where `control` is a +control's `name`, else its text, and `value` is an edit field's text, a slider's number (kept in its range), or a +list's item index or `null`. The dialog takes the next step each time it waits. The run ends with an error that +the script cannot catch, and every document goes back, when no step is left, when a step names a control the +dialog does not have or that cannot take it, or when the dialog closes with steps it did not use. + +```sh +vectorcraft-cli run --cmd script.run --params '{"source": "var w = new Window(\"dialog\", \"Frame\"); var name = w.add(\"edittext\", undefined, \"Frame\", {name: \"name\"}); w.add(\"button\", undefined, \"OK\"); w.add(\"button\", undefined, \"Cancel\"); if (w.show() == 1) vc.log(name.text);", "answers": [{"kind": "window", "value": [{"control": "name", "event": "change", "value": "Border"}, {"control": "OK", "event": "click"}]}]}' +``` + The help pages https://extendscript.docsforadobe.dev/file-system-access/file-object/ and https://extendscript.docsforadobe.dev/file-system-access/folder-object/ describe the `File` and `Folder` objects. A script reads files with them: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..939047032e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1066,6 +1066,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Custom arrowheads under `--automation-read-root`: `stroke.arrowheads.list` gives `file` as `null` for an arrowheads file outside the read roots and names it by its file name in `error`, and `stroke.arrowheads.edit` and `stroke.arrowheads.reload` refuse such a file before anything is made, opened, brought to the front or read; inside the roots `edit` opens the file under the client's roots. `crates/engine/src/tests/arrowheads.rs` (`an_agent_outside_the_arrowheads_files_folder_sees_its_file_name_alone_and_cannot_reload_it`, `an_agent_edits_the_arrowheads_file_only_inside_its_read_roots`). - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`). - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. + - Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person, runs the controls' `onClick`, `onChanging`, `onChange`, `onShow` and `onClose` handlers, and returns the result of `close(result)`, 1 for the default button or 2 for the cancel button; a run over MCP or the command line takes the clicks and changes from a `window` answer. Palettes, other control types and resource strings throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse. - Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`).