From 26e0cef48dad241c0e387c6dbb101c91c9a9f06c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:19:11 -0800 Subject: [PATCH 01/34] Scripts: ScriptUI palettes stay open after the run and run their handlers in line new Window("palette") in a script with a named #targetengine shows a palette that stays open beside the documents after the run ends. show() runs onShow and returns at once; hide(), show() and close() work as for a dialog, and close() and the close box run onClose. Each click, change or close on a palette runs its handler as a run of its own in the palette's engine, with its own report and undo step. While another run goes on, the event waits and runs after it, oldest first; a newer event for the same control or close replaces a waiting one. An error in a handler ends that run and leaves the palette open. A palette in a script without #targetengine, or with #targetengine main, throws an Error that asks for a #targetengine line. Palettes close when their engine is dropped or ends with an internal error, and when the session ends. A session keeps at most 16 palettes and 64 waiting events. script.palettes lists the palettes and their controls, and script.palette.event gives a palette a click, change or close. The script checker lists palettes under dialogs instead of hostOnly. --- crates/engine/src/cmd/scripts.rs | 45 +- crates/engine/src/lib.rs | 3 + crates/engine/src/script/files.rs | 10 +- crates/engine/src/script/mod.rs | 35 +- crates/engine/src/script/palettes.rs | 347 ++++++++++++++ crates/engine/src/script/scriptui.rs | 93 +++- crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_palettes.rs | 312 +++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/js/src/realm.rs | 10 + crates/js/src/scriptui.rs | 425 ++++++++++++++---- crates/js/src/scriptui_tests.rs | 126 +++++- crates/scriptcheck/src/catalog.rs | 2 +- crates/scriptcheck/src/lib.rs | 4 +- crates/scriptcheck/src/tests.rs | 6 + crates/ui-egui/src/app.rs | 6 + crates/ui-egui/src/dialogs/script_window.rs | 8 +- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 33 ++ crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/script_palettes.rs | 93 ++++ crates/ui-egui/src/script_runs.rs | 6 +- crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/script_palettes.rs | 109 +++++ docs/mcp.md | 50 ++- docs/target-app-parity.md | 3 +- 51 files changed, 1649 insertions(+), 108 deletions(-) create mode 100644 crates/engine/src/script/palettes.rs create mode 100644 crates/engine/src/tests/script_palettes.rs create mode 100644 crates/ui-egui/src/script_palettes.rs create mode 100644 crates/ui-egui/src/tests/script_palettes.rs diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index fd02b3a9a1..831b56c586 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, else its text)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar, 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", + "{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, windows and resource strings throw that they are not available yet); new Window(\"palette\", title) builds a palette the same way, only in a script with #targetengine and a name other than main (elsewhere it throws an error that says so): its show() returns at once and the palette stays open after the run, beside the documents, until close(), the close box (each runs onClose, which can keep it open by returning false) or the end of its engine or the session; each click, change or close the person gives it runs its handler as a run of its own in that engine, once no run is going, oldest first, and a newer one for the same control or the same close takes a waiting one's place (script.palettes, script.palette.event; at most 16 palettes and 64 waiting events); show() on a dialog 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 ), @@ -63,6 +63,24 @@ pub fn specs() -> Vec { always, engine_drop ), + cmd!( + query "script.palettes", + "List Script Palettes", + [], + None, + "{} the ScriptUI palettes that runs in named engines showed and have not closed, shown or hidden, in the order they were first shown, and the events that wait for a run → {palettes: [{id, engine, title, visible, controls: [{index, kind, name, text, enabled, visible, value (check box, radio button, slider, progress bar), items and selection (lists)}]}], waiting: events waiting, limit: 16, waitingLimit: 64}", + always, + palettes + ), + cmd!( + query "script.palette.event", + "Script Palette Event", + [], + None, + "{palette: an id script.palettes lists, event: click|change|close, control?: a control's index, or its name or text (click and change), value?: an edit field's text, a slider's number, or a list's item index or null (change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; while it waits, another click on the same control, change of it or close of the same palette takes its place with the newer value, and a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", + always, + palette_event + ), cmd!( query "script.console", "Script Console", @@ -245,6 +263,31 @@ fn engine_drop(s: &mut Session, p: &Value) -> Result { Ok(json!({"dropped": true, "name": name})) } +fn palettes(s: &mut Session, _: &Value) -> Result { + let list: Vec = s.script_palettes().iter().map(script::palettes::palette_json).collect(); + Ok(json!({ + "palettes": list, + "waiting": s.script_palette_events_waiting(), + "limit": script::palettes::MAX_PALETTES, + "waitingLimit": script::palettes::MAX_WAITING, + })) +} + +fn palette_event(s: &mut Session, p: &Value) -> Result { + const C: &str = "script.palette.event"; + let Some(id) = p.get("palette").and_then(Value::as_u64) else { + return Err(bad(C, "`palette` must be a palette's id, as script.palettes lists it")); + }; + let Some(event) = p.get("event").and_then(Value::as_str) else { return Err(bad(C, "`event` must be click, change or close")) }; + let Some(palette) = s.script_palettes().iter().find(|q| q.id == id) else { return Err(bad(C, format!("there is no script palette {id}"))) }; + let event = script::palettes::parse_event(&palette.dialog, event, p.get("control"), p.get("value")).map_err(|e| bad(C, e))?; + let waiting = s.script_palette_event(id, event).map_err(|e| bad(C, e))?; + if s.script_frames { + return Ok(json!({"waiting": true, "merged": waiting == script::Waiting::Merged, "waitingEvents": s.script_palette_events_waiting()})); + } + s.script_palette_run_waiting() +} + fn console_lines(s: &mut Session, _: &Value) -> Result { Ok(s.script_console().to_json()) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 68067dc697..5a790a06d9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -312,6 +312,9 @@ pub struct Session { pub(crate) script_high_water: std::collections::HashMap, /// While a slice of a script runs in this session. pub(crate) script_in_run: bool, + /// The ScriptUI palettes the named engines' runs showed, and the events that wait for a run + /// ([`script::palettes`]). + pub(crate) script_palettes: script::palettes::Palettes, /// Write recovery copies of the unsaved documents before a run, and don't start without them. pub script_copy_first: bool, /// While the active tool's actions run: their commands aren't "a command from outside the diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 94ef3bdf9e..467e148696 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -216,6 +216,9 @@ pub(crate) struct Setup { pub script: Option, /// The script's text with the files it includes, whose SHA-256 the grants it keeps are for. pub source: String, + /// The SHA-256 the grants are for in place of `source`'s: for the run of a ScriptUI palette's + /// handler, the one of the script that showed the palette. + pub own: Option, /// The folder that holds each script's data folder ([`crate::Session::attach_script_data`]). pub data_dir: Option, /// The code the run's named engine kept from its earlier runs: the SHA-256 of each source @@ -302,7 +305,7 @@ impl Disk { let start = scope.folder().map_or_else(|| home.clone(), |p| p.to_string_lossy().into_owned()); let web = cfg!(target_arch = "wasm32"); let script = setup.script.as_deref().filter(|_| !web).and_then(|p| std::fs::canonicalize(p).ok()); - let own = vectorcraft_plugins::permissions::sha256_hex(setup.source.as_bytes()); + let own = setup.own.unwrap_or_else(|| vectorcraft_plugins::permissions::sha256_hex(setup.source.as_bytes())); let script = script.map(|p| (p, own.clone())); let fenced = setup.data_dir.as_deref().filter(|_| !web).and_then(Path::parent).and_then(real_or_planned); let held = scope.roots().iter().map(|r| (r.clone(), false, true)).collect(); @@ -373,6 +376,11 @@ impl Disk { } } + /// The SHA-256 the run's grants are for ([`Setup::own`]). + pub(crate) fn own(&self) -> &str { + &self.own + } + /// Adds the source with SHA-256 `hash` to what the run's code may run. → whether it was new. fn saw(&mut self, hash: String) -> bool { if self.ran_too_much || self.ran.contains(&hash) || self.own == hash { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index cb0398500a..de8f299cec 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -47,14 +47,20 @@ //! run. An engine keeps no document and no run: its host functions reach the run through a link //! that holds the run's host only while the run goes on. An error, a limit or a stop puts the //! documents back and keeps the engine's globals; an internal error drops the engine. +//! +//! A run in a named engine can show ScriptUI palettes ([`palettes`]), which stay open after it and +//! whose events run as runs of their own in that engine, one at a time once no run is going. A +//! palette closes with its engine. pub mod console; pub mod dialogs; pub mod dollar; pub mod include; +pub mod palettes; pub mod scriptui; pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog}; +pub use palettes::{ScriptPalette, Waiting}; pub use scriptui::{ScriptUiDialog, UiEvent, UiKind, UiValue}; use std::cell::{Cell, RefCell}; @@ -801,6 +807,13 @@ struct Host { dollar: dollar::RunState, /// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it. args: RefCell<(Data, u64)>, + /// The named engine the run is in; `None` for a new realm. + engine: Option, + /// The script file the run was read from; `None` for a script given as text. + file: Option, + /// For the run of a palette's handler, the palette's id and the event, until the palette takes + /// it ([`palettes`]). + palette_event: RefCell>, } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -1686,6 +1699,7 @@ impl Session { match gone { Some(engine) => { drop(engine); + self.keep_engines_palettes(); Ok(()) } None => Err(EngineError::Other(format!("there is no script engine named {name:?}"))), @@ -1933,6 +1947,7 @@ impl Session { lost }); drop(lost); + self.keep_engines_palettes(); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -1954,6 +1969,7 @@ impl Session { /// Begins a run of `request`. → the run's name. pub(crate) fn script_start(&mut self, request: Request) -> Result { + let palette_event = self.script_palettes.starting.take(); self.settle_for_script()?; // In a build where a fault ends the program, every unsaved document has a copy first. if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() { @@ -2048,6 +2064,7 @@ impl Session { script: request.file.clone(), // The text with its included files, so a changed included file asks again. source: expanded.as_ref().map_or_else(|_| request.source.clone(), |e| e.source.clone()), + own: palette_event.as_ref().and_then(|q| q.grants.clone()), data_dir: self.script_data_dir.clone(), engine_code: kept_maps.as_ref().map_or_else(Default::default, |m| { let m = m.borrow(); @@ -2068,6 +2085,9 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), + engine: engine.clone(), + file: request.file.clone(), + palette_event: RefCell::new(palette_event), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { @@ -2122,6 +2142,7 @@ impl Session { // error drops a kept one. let keep = !fresh && e.kind != RunErrorKind::Internal; self.return_engine(engine.as_deref(), &link, keep.then_some(realm)); + self.keep_engines_palettes(); let mut report = failure_report(&name, &e, file.as_deref(), &host, 0, 0); close_run(self, &host, &mut report, ending(&e.kind)); let message = failure_text(&report); @@ -2212,6 +2233,7 @@ impl Session { let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left)); close_run(self, &job.host, &mut report, ending(&e.kind)); self.end_job(job, e.kind == RunErrorKind::Internal); + self.keep_engines_palettes(); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -2481,6 +2503,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result std::result::Result realm.refresh_script_ui().map(|()| Progress::Done(v)), + // A failed run keeps its globals, so its palettes show what it left too; a refresh + // that fails as well (the fuel is spent, a stop) leaves them as they were. + Err(e) if named && e.kind != RunErrorKind::Internal => { + let _ = realm.refresh_script_ui(); + Err(e) + } + r => r, + } }) }); if let Some(started) = started { diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs new file mode 100644 index 0000000000..d6ff578f29 --- /dev/null +++ b/crates/engine/src/script/palettes.rs @@ -0,0 +1,347 @@ +//! ScriptUI palettes (`new Window("palette")`, [`vectorcraft_js::scriptui`]): windows a run in a +//! named engine (`#targetengine`) shows, which stay open after the run ends and take clicks and +//! changes while the person goes on working. +//! +//! A palette needs a named engine, which keeps its controls and handlers between runs: in a script +//! without `#targetengine`, or with `main`, `new Window("palette")` throws. `show()` returns at once. +//! Each click, change or close the person gives a palette waits here, and then runs as a run of its +//! own in the palette's engine, which takes the mutation lease like any other run: one event at a +//! time, oldest first, each starting only once no run is going. While an event waits, another click +//! on the same control, another change of it or another close of the same palette takes its place +//! in line, with the newer value, instead of waiting as well. +//! +//! A palette closes when its script calls `close()` or the person closes it, unless `onClose` +//! returns `false`; when its engine is dropped or ends with an internal error; and with the session. +//! Hiding or closing a palette drops the events that wait for it. An error in a handler ends that +//! handler's run like any failed run, with its report, and leaves the palette open. +//! +//! The limits here are VectorCraft's own: [`MAX_PALETTES`] and [`MAX_WAITING`]. + +use std::collections::VecDeque; + +use serde_json::{Map, Value, json}; + +use super::scriptui::{self, ScriptUiDialog, UiEvent, UiKind, UiValue}; +use crate::{EngineError, Result, Session}; + +/// The most palettes a session keeps, shown or hidden. +pub const MAX_PALETTES: usize = 16; +/// The most events that wait for a run, for every palette together. +pub const MAX_WAITING: usize = 64; + +/// A palette a run showed. +#[derive(Clone, Debug, PartialEq)] +pub struct ScriptPalette { + /// Its number in the session, which no other palette of the session has had. + pub id: u64, + /// The named engine its handlers run in. + pub engine: String, + /// The script file of the run that first showed it, whose folder its handlers read in; `None` + /// for a script given as text. + pub file: Option, + /// Its controls, as the last `show()`, `add()` or handler left them. + pub dialog: ScriptUiDialog, + pub visible: bool, + /// The SHA-256 the file grants of the script that first showed it are kept for, which its + /// handlers' runs keep using. + pub(crate) grants: String, +} + +/// What became of an event given to a palette. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Waiting { + /// It waits at the end of the line. + Added, + /// It took the place of a waiting event for the same control. + Merged, +} + +/// An event given to a palette, waiting for its run or handed to it. +#[derive(Clone, Debug)] +pub(crate) struct Queued { + pub(crate) palette: u64, + pub(crate) event: UiEvent, + /// For a list's change, the list's items as the palette showed them when the event was given and + /// the list's revision then ([`super::scriptui::UiNode::revision`]), which the run checks the list + /// still has. + pub(crate) list: Option<(Vec, f64)>, + /// Once its run starts, the SHA-256 the file grants of the palette's script are kept for, which + /// the run takes as its own ([`super::files::Setup::own`]). + pub(crate) grants: Option, +} + +/// The palettes of a session, and the events that wait for a run. +#[derive(Debug, Default)] +pub(crate) struct Palettes { + list: Vec, + waiting: VecDeque, + last_id: u64, + /// The event the run that starts next handles ([`Session::script_palette_start`]). + pub(crate) starting: Option, +} + +/// Do `a` and `b` share one place in line: a click on the same control, a change of it, or a close? +fn same_place(a: &UiEvent, b: &UiEvent) -> bool { + match (a, b) { + (UiEvent::Click(x), UiEvent::Click(y)) | (UiEvent::Change(x, _), UiEvent::Change(y, _)) => x == y, + (UiEvent::Close, UiEvent::Close) => true, + _ => false, + } +} + +impl Palettes { + fn find(&mut self, id: u64, engine: &str) -> Option<&mut ScriptPalette> { + self.list.iter_mut().find(|p| p.id == id && p.engine == engine) + } + + /// `show()`: shows the palette `id` of `engine` with `dialog`, or a new one without `id`. → its id. + pub(crate) fn show( + &mut self, + id: Option, + engine: &str, + (file, grants): (Option, String), + dialog: ScriptUiDialog, + ) -> std::result::Result { + if let Some(p) = id.and_then(|id| self.find(id, engine)) { + p.dialog = dialog; + p.visible = true; + return Ok(p.id); + } + if self.list.len() >= MAX_PALETTES { + return Err(format!("show: a session keeps at most {MAX_PALETTES} script palettes; close one first")); + } + self.last_id += 1; + self.list.push(ScriptPalette { id: self.last_id, engine: engine.to_string(), file, dialog, visible: true, grants }); + Ok(self.last_id) + } + + /// The palette's controls as a handler or `add()` left them. → false when it is closed. + pub(crate) fn update(&mut self, id: u64, engine: &str, dialog: ScriptUiDialog) -> bool { + let Some(p) = self.find(id, engine) else { return false }; + p.dialog = dialog; + true + } + + /// `hide()`. → false when it is closed. + pub(crate) fn hide(&mut self, id: u64, engine: &str) -> bool { + let Some(p) = self.find(id, engine) else { return false }; + p.visible = false; + self.waiting.retain(|q| q.palette != id); + true + } + + /// `close()`, once `onClose` allowed it. → false when it was closed already. + pub(crate) fn close(&mut self, id: u64, engine: &str) -> bool { + let before = self.list.len(); + self.list.retain(|p| !(p.id == id && p.engine == engine)); + self.waiting.retain(|q| q.palette != id); + self.list.len() != before + } + + /// Closes the palettes of the engines `keep` does not keep, with their waiting events. + fn keep_engines(&mut self, keep: impl Fn(&str) -> bool) { + self.list.retain(|p| keep(&p.engine)); + let open: Vec = self.list.iter().map(|p| p.id).collect(); + self.waiting.retain(|q| open.contains(&q.palette)); + } + + /// Puts `event` for the shown palette `id` in line, once it is checked against the palette. + fn wait(&mut self, id: u64, event: UiEvent) -> std::result::Result { + let Some(p) = self.list.iter().find(|p| p.id == id) else { return Err(format!("there is no script palette {id}")) }; + if !p.visible { + return Err(format!("the script palette {id} is hidden")); + } + let event = scriptui::check_event(&p.dialog, event)?; + let list = match &event { + UiEvent::Change(c, UiValue::Index(_)) => p.dialog.nodes.get(*c).map(|n| (n.items.clone(), n.revision)), + _ => None, + }; + if let Some(slot) = self.waiting.iter_mut().find(|q| q.palette == id && same_place(&q.event, &event)) { + slot.event = event; + slot.list = list; + return Ok(Waiting::Merged); + } + if self.waiting.len() >= MAX_WAITING { + return Err(format!("{MAX_WAITING} script palette events already wait; this one was not kept")); + } + self.waiting.push_back(Queued { palette: id, event, list, grants: None }); + Ok(Waiting::Added) + } + + /// The oldest waiting event whose palette is still shown, and that palette. + fn next(&mut self) -> Option<(ScriptPalette, Queued)> { + while let Some(q) = self.waiting.pop_front() { + if let Some(p) = self.list.iter().find(|p| p.id == q.palette && p.visible) { + return Some((p.clone(), q)); + } + } + None + } +} + +/// `name` in a `#targetengine` line, quoted with a quote it does not hold. +fn engine_line(name: &str) -> String { + let quote = if name.contains('"') { '\'' } else { '"' }; + format!("#targetengine {quote}{name}{quote}") +} + +/// The source of a palette's handler run: its engine, and the call that hands the event to the +/// palette, which takes it from the run's host. +fn handler_source(engine: &str) -> String { + format!("{}\nWindow.__vcPaletteEvent();\n", engine_line(engine)) +} + +/// The event `event` (`click`, `change` or `close`) for `dialog`, from `script.palette.event`'s +/// `control` (a control's index, or its name or text) and `value` (an edit field's text, a slider's +/// number, or a list's item index or null). +pub(crate) fn parse_event( + dialog: &ScriptUiDialog, + event: &str, + control: Option<&Value>, + value: Option<&Value>, +) -> std::result::Result { + if event == "close" { + if control.is_some() || value.is_some() { + return Err("a close takes no `control` and no `value`".into()); + } + return Ok(UiEvent::Close); + } + let id = match 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)) => dialog.find(s).ok_or_else(|| format!("the palette has no control named {}", super::dialogs::cut_to(s, 64)))?, + _ => return Err("`control` must be a control's index, name or text".into()), + }; + let list = dialog.nodes.get(id).is_some_and(|n| matches!(n.kind, UiKind::DropDownList | UiKind::ListBox)); + let event = match (event, value) { + ("click", None) => UiEvent::Click(id), + ("click", Some(_)) => return Err("a click takes no `value`".into()), + ("change", Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())), + ("change", Some(Value::Number(v))) if list => match v.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()), + }, + ("change", Some(Value::Number(v))) => UiEvent::Change(id, UiValue::Number(v.as_f64().unwrap_or(f64::NAN))), + ("change", Some(Value::Null)) if list => UiEvent::Change(id, UiValue::Index(None)), + ("change", _) => return Err("a change's `value` must be a string, a number, or for a list an item index or null".into()), + _ => return Err("`event` must be click, change or close".into()), + }; + scriptui::check_event(dialog, event) +} + +/// A palette as `script.palettes` lists it. +pub(crate) fn palette_json(p: &ScriptPalette) -> Value { + let controls: Vec = p + .dialog + .nodes + .iter() + .enumerate() + .skip(1) + .map(|(i, n)| { + let mut c = Map::new(); + c.insert("index".into(), json!(i)); + c.insert("kind".into(), json!(kind_id(n.kind))); + c.insert("name".into(), json!(n.name)); + c.insert("text".into(), json!(n.text)); + c.insert("enabled".into(), json!(n.enabled)); + c.insert("visible".into(), json!(n.visible)); + match n.kind { + UiKind::CheckBox | UiKind::RadioButton => { + c.insert("value".into(), json!(n.checked)); + } + UiKind::Slider | UiKind::ProgressBar => { + c.insert("value".into(), json!(n.value)); + } + UiKind::DropDownList | UiKind::ListBox => { + c.insert("items".into(), json!(n.items)); + c.insert("selection".into(), json!(n.selection)); + } + _ => {} + } + Value::Object(c) + }) + .collect(); + json!({"id": p.id, "engine": p.engine, "title": p.dialog.title(), "visible": p.visible, "controls": controls}) +} + +fn kind_id(kind: UiKind) -> &'static str { + match kind { + UiKind::Dialog => "palette", + UiKind::Group => "group", + UiKind::Panel => "panel", + UiKind::StaticText => "statictext", + UiKind::EditText => "edittext", + UiKind::Button => "button", + UiKind::CheckBox => "checkbox", + UiKind::RadioButton => "radiobutton", + UiKind::DropDownList => "dropdownlist", + UiKind::ListBox => "listbox", + UiKind::Slider => "slider", + UiKind::ProgressBar => "progressbar", + } +} + +impl Session { + /// The palettes the named engines' runs showed and have not closed, shown or hidden, in the + /// order they were first shown. + pub fn script_palettes(&self) -> &[ScriptPalette] { + &self.script_palettes.list + } + + /// How many palette events wait for a run. + pub fn script_palette_events_waiting(&self) -> usize { + self.script_palettes.waiting.len() + } + + /// Puts `event` for the shown palette `id` in line, to run in its engine once no run is going + /// ([`Session::script_palette_start`]). → an error when there is no such shown palette, it + /// cannot take the event ([`scriptui::check_event`]), or [`MAX_WAITING`] events already wait. + pub fn script_palette_event(&mut self, id: u64, event: UiEvent) -> std::result::Result { + self.script_palettes.wait(id, event) + } + + /// Starts the run of the oldest waiting palette event, when no run is going. → `None` when a + /// run is going or no event waits; otherwise the run's name, or the error that ended it before + /// it began. + pub fn script_palette_start(&mut self) -> Option> { + // An event waits while a drag or an undo group is open, which a run cannot start in. + if self.script_running() || self.script_palettes.waiting.is_empty() || self.settle_for_script().is_err() { + return None; + } + let (palette, mut queued) = self.script_palettes.next()?; + queued.grants = Some(palette.grants.clone()); + let title = palette.dialog.title(); + let name = if title.is_empty() { "palette".to_string() } else { super::dialogs::cut_to(title, super::dialogs::MAX_TITLE_BYTES).to_string() }; + let locale = super::dollar::ui_locale(self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language)); + let request = super::Request { + name, + name_given: true, + file: palette.file.clone(), + checked_real: None, + source: handler_source(&palette.engine), + args: Map::new(), + fuel: super::DEFAULT_FUEL, + locale, + answers: Vec::new(), + }; + self.script_palettes.starting = Some(queued); + let r = self.script_start(request); + self.script_palettes.starting = None; + Some(r) + } + + /// Closes the palettes whose engine the session no longer keeps. + pub(crate) fn keep_engines_palettes(&mut self) { + let names: Vec = self.script_engines().into_iter().map(|(name, ..)| name).collect(); + self.script_palettes.keep_engines(|e| names.iter().any(|n| n == e)); + } + + /// `script.palette.event` with no run going and nobody to ask: runs the waiting events in turn, + /// the one just given last. → that one's report. + pub(crate) fn script_palette_run_waiting(&mut self) -> Result { + let mut last = Err(EngineError::Other("no script palette event waits".into())); + while let Some(started) = self.script_palette_start() { + last = started.and_then(|_| self.script_run_to_end()); + } + last + } +} diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index 2f77fbb5b8..8ca7154e47 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -1,6 +1,9 @@ //! 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. +//! person or `script.run`'s `answers` give back. A palette (`new Window("palette")`) is described +//! and laid out the same way; [`super::palettes`] keeps it and its events, and the host functions +//! `palette`, `paletteShow`, `paletteUpdate`, `paletteHide`, `paletteClose` and `paletteEvent` here +//! act for a run in a named engine, and throw [`PALETTE_NEEDS_ENGINE`] in any other. //! //! 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 @@ -136,6 +139,9 @@ pub struct UiNode { pub max: f64, pub items: Vec, pub selection: Option, + /// How many times a list's items were added or removed, which a palette's waiting change of + /// the list is checked against. + pub revision: f64, pub multiline: bool, pub readonly: bool, pub rect: UiRect, @@ -497,6 +503,7 @@ pub fn parse(d: &Data) -> Result { max, items, selection, + revision: number(field(f, "revision")).unwrap_or(0.0), multiline: flag("multiline"), readonly: flag("readonly"), rect: UiRect::default(), @@ -668,7 +675,89 @@ fn function(link: &super::Link, f: fn(&Host, &[Data]) -> Result /// 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))]) + realm.define_script_ui(vec![ + ("open".into(), function(link, open)), + ("wait".into(), function(link, wait)), + ("end".into(), function(link, end)), + ("palette".into(), function(link, palette)), + ("paletteShow".into(), function(link, palette_show)), + ("paletteUpdate".into(), function(link, palette_update)), + ("paletteHide".into(), function(link, palette_hide)), + ("paletteClose".into(), function(link, palette_close)), + ("paletteEvent".into(), function(link, palette_event)), + ]) +} + +/// The error of `new Window("palette")` in a run without a named engine. +pub const PALETTE_NEEDS_ENGINE: &str = "Window: a palette needs a named engine, which keeps its controls and handlers after the script ends; put a #targetengine line with a name other than main at the top of the script"; + +/// The named engine of the run, for a palette. +fn palette_engine(host: &Host) -> Result<&str, HostError> { + host.engine.as_deref().ok_or_else(|| HostError::Error(PALETTE_NEEDS_ENGINE.into())) +} + +/// A palette's id as a script holds it: a whole number from 1, or none. +fn palette_id(d: Option<&Data>) -> Option { + match d { + Some(Data::Number(n)) if *n >= 1.0 && n.fract() == 0.0 && *n < 9.0e15 => Some(*n as u64), + _ => None, + } +} + +/// `new Window("palette")`: refused in a run without a named engine. +fn palette(host: &Host, _: &[Data]) -> Result { + palette_engine(host)?; + Ok(Data::Undefined) +} + +/// A palette's `show()`, with its description and its id (none the first time). → its id. +fn palette_show(host: &Host, args: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + let dialog = described(host, args)?; + let id = palette_id(args.get(1)); + let grants = host.disk.borrow().own().to_string(); + let shown = host.session.borrow_mut().script_palettes.show(id, &engine, (host.file.clone(), grants), dialog); + shown.map(|id| Data::Number(id as f64)).map_err(HostError::Range) +} + +/// The palette `id`'s controls as a handler or `add()` left them. +fn palette_update(host: &Host, args: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + let dialog = described(host, args)?; + if let Some(id) = palette_id(args.get(1)) { + host.session.borrow_mut().script_palettes.update(id, &engine, dialog); + } + Ok(Data::Undefined) +} + +fn palette_hide(host: &Host, args: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + if let Some(id) = palette_id(args.first()) { + host.session.borrow_mut().script_palettes.hide(id, &engine); + } + Ok(Data::Undefined) +} + +fn palette_close(host: &Host, args: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + if let Some(id) = palette_id(args.first()) { + host.session.borrow_mut().script_palettes.close(id, &engine); + } + Ok(Data::Undefined) +} + +/// The event a palette handler's run is for, once: `{palette, event, id, value, items}`, as `show()` +/// takes a dialog's event with the palette's id added, and for a list's change the items the +/// palette showed; `null` for any other run, and after the first call. +fn palette_event(host: &Host, _: &[Data]) -> Result { + let Some(queued) = host.palette_event.borrow_mut().take() else { return Ok(Data::Null) }; + let Data::Object(mut fields) = queued.event.data() else { return Ok(Data::Null) }; + fields.push(("palette".into(), Data::Number(queued.palette as f64))); + if let Some((items, revision)) = queued.list { + fields.push(("items".into(), Data::Array(items.into_iter().map(Data::String).collect()))); + fields.push(("revision".into(), Data::Number(revision))); + } + Ok(Data::Object(fields)) } fn described(host: &Host, args: &[Data]) -> Result { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1685adc40f..55395c0d01 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -170,6 +170,7 @@ impl Session { script_frames: false, script_high_water: Default::default(), script_in_run: false, + script_palettes: Default::default(), script_copy_first: cfg!(target_arch = "wasm32"), } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 58addcd9fe..c655eea8b5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -176,6 +176,7 @@ mod script_engines; mod script_folder; mod script_include; mod script_io; +mod script_palettes; mod script_run; mod script_scriptui; mod scripts; diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs new file mode 100644 index 0000000000..006f022627 --- /dev/null +++ b/crates/engine/src/tests/script_palettes.rs @@ -0,0 +1,312 @@ +//! ScriptUI palettes in a script: a named engine to show them in, the events that wait for a run +//! and run one at a time after it, the events that take a waiting one's place, `close()` and the +//! close box, the engine's end, and the limits. + +use serde_json::{Value, json}; + +use crate::script::palettes::{MAX_PALETTES, MAX_WAITING}; +use crate::script::scriptui::PALETTE_NEEDS_ENGINE; +use crate::script::{DialogAnswer, UiEvent, Waiting}; +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 run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "p.js"})) +} + +/// Pumps the run in the app until it ends, or until it waits at a dialog (`None`). +fn pump(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_dialog().is_some() || s.script_window().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +/// Runs `source` in the app to its end. +fn run_in_app(s: &mut Session, source: &str) -> Value { + s.script_frames = true; + assert_eq!(run(s, source).unwrap()["running"], true); + pump(s).expect("the run ended").unwrap() +} + +/// A palette in the engine `tools` with a button (control 1) whose handler counts its clicks and +/// adds a rectangle, and a field (control 2). +const TOOLS: &str = "#targetengine tools\n\ + var clicks = 0; var p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ + var field = p.add('edittext', undefined, ''); \ + go.onClick = function () { clicks++; vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); vc.log('click ' + clicks); }; \ + field.onChange = function () { vc.log('change ' + field.text); }; p.show(); vc.log('shown');"; + +fn only_palette(s: &Session) -> u64 { + let list = s.script_palettes(); + assert_eq!(list.len(), 1, "{list:?}"); + list[0].id +} + +#[test] +fn show_returns_at_once_and_the_palette_stays_after_the_run() { + let mut s = one_doc(); + let r = run(&mut s, TOOLS).unwrap(); + assert_eq!(r["log"], json!(["shown"]), "show() did not wait: {r}"); + let id = only_palette(&s); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["engine"], "tools"); + assert_eq!(listed["palettes"][0]["title"], "Tools"); + assert_eq!(listed["palettes"][0]["controls"][0]["text"], "Go"); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": "Go"})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"])); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script", "a handler's run is one undo step"); + let changed = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 2, "value": "abc"})).unwrap(); + assert_eq!(changed["log"], json!(["change abc"])); +} + +#[test] +fn a_later_run_in_the_engine_changes_what_the_palette_shows() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + run(&mut s, "#targetengine tools\ngo.enabled = false; go.text = 'Wait';").unwrap(); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["controls"][0]["enabled"], false, "{listed}"); + assert_eq!(listed["palettes"][0]["controls"][0]["text"], "Wait"); + assert!(s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).is_err(), "a disabled button takes no click"); +} + +#[test] +fn a_handler_keeps_the_file_grants_of_the_script_that_showed_the_palette() { + let base = std::env::temp_dir().join(format!("vc-script-palette-grants-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("picked")).unwrap(); + let base = std::fs::canonicalize(&base).unwrap(); + let data = base.join("picked/data.txt"); + std::fs::write(&data, "hello").unwrap(); + let path = serde_json::to_string(&data.to_string_lossy()).unwrap(); + let main = base.join("main/main.jsx"); + let source = format!( + "#targetengine grants\nif (typeof picked == 'undefined') {{ var picked = File.openDialog('p'); }} \ + var p = new Window('palette'); var b = p.add('button', undefined, 'Read'); \ + b.onClick = function () {{ var f = new File({path}); vc.log(f.open('r') ? f.read() : f.error); }}; p.show();" + ); + std::fs::write(&main, source).unwrap(); + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); + for _ in 0..10_000 { + if s.script_picker().is_some() { + break; + } + assert!(s.script_pump().is_none(), "the run waits at its file dialog"); + } + let picked = data.to_string_lossy().into_owned(); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![picked], always: true })); + pump(&mut s).expect("the run ended").unwrap(); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("the handler ended").unwrap()["log"], json!(["hello"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_failed_run_in_the_engine_still_changes_what_the_palette_shows() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + assert!(run(&mut s, "#targetengine tools\ngo.enabled = false; throw new Error('after');").is_err()); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["controls"][0]["enabled"], false, "{listed}"); +} + +#[test] +fn a_list_change_that_waited_while_the_list_changed_ends_its_run() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine lists\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ + l.onChange = function () { vc.log(String(l.selection)); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "#targetengine lists\nconfirm('Go?'); l.removeAll(); l.add('item', 'a'); l.add('item', 'b');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + let pick = UiEvent::Change(1, crate::script::UiValue::Index(Some(1))); + assert_eq!(s.script_palette_event(id, pick.clone()), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the change starts its run").is_ok()); + let e = pump(&mut s).unwrap().unwrap_err().to_string(); + assert!(e.contains("a palette's list changed before the person's choice was taken"), "{e}"); + assert_eq!(s.script_palette_event(id, pick), Ok(Waiting::Added), "a change given after it is for the new items"); + assert!(s.script_palette_start().unwrap().is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["b"])); +} + +#[test] +fn a_palette_click_during_another_run_runs_after_it() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + let id = only_palette(&s); + assert_eq!(run(&mut s, "var a = confirm('Go?'); vc.log('busy done');").unwrap()["running"], true); + assert!(pump(&mut s).is_none(), "the run waits at its confirm"); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(s.script_palette_start().is_none(), "the click waits while another run holds the lease"); + assert_eq!(s.script_palette_events_waiting(), 1); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["busy done"])); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["click 1"])); + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn double_clicks_while_queued_run_once() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Merged)); + let text = |t: &str| UiEvent::Change(2, crate::script::UiValue::Text(t.into())); + assert_eq!(s.script_palette_event(id, text("a")), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, text("ab")), Ok(Waiting::Merged), "a later change takes the waiting one's place"); + assert_eq!(s.script_palette_events_waiting(), 2); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + let mut logs = vec![]; + while let Some(started) = s.script_palette_start() { + started.unwrap(); + logs.push(pump(&mut s).unwrap().unwrap()["log"].clone()); + } + assert_eq!(logs, [json!(["click 1"]), json!(["change ab"])]); +} + +#[test] +fn a_palette_from_a_script_without_a_named_engine_is_refused() { + let mut s = one_doc(); + for source in ["", "#targetengine main\n"] { + let r = run(&mut s, &format!("{source}try {{ new Window('palette'); }} catch (e) {{ vc.log(e.message); }}")).unwrap(); + assert_eq!(r["log"], json!([PALETTE_NEEDS_ENGINE]), "{source:?}"); + } + assert!(s.script_palettes().is_empty()); +} + +#[test] +fn close_fires_on_close_and_frees_the_window() { + let mut s = one_doc(); + run(&mut s, &format!("{TOOLS} p.onClose = function () {{ vc.log('closing'); }};")).unwrap(); + let id = only_palette(&s); + let closed = s.execute("script.palette.event", &json!({"palette": id, "event": "close"})).unwrap(); + assert_eq!(closed["log"], json!(["closing"])); + assert!(s.script_palettes().is_empty(), "the close box freed the palette"); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains(&format!("there is no script palette {id}")), "{e}"); + + run(&mut s, TOOLS).unwrap(); + let r = + run(&mut s, "#targetengine tools\nvar asked = 0; p.onClose = function () { asked++; return asked > 1; }; p.close(); vc.log(asked);").unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(s.script_palettes().len(), 1, "onClose returned false: the palette stays open"); + run(&mut s, "#targetengine tools\np.close();").unwrap(); + assert!(s.script_palettes().is_empty(), "close() freed the palette"); +} + +#[test] +fn dropping_the_engine_closes_its_palettes() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + run_in_app(&mut s, "#targetengine other\nnew Window('palette').show();"); + let id = s.script_palettes()[0].id; + s.script_palette_event(id, UiEvent::Click(1)).unwrap(); + s.execute("script.engine.drop", &json!({"name": "tools"})).unwrap(); + let left: Vec<&str> = s.script_palettes().iter().map(|p| p.engine.as_str()).collect(); + assert_eq!(left, ["other"]); + assert_eq!(s.script_palette_events_waiting(), 0, "the dropped palette's event no longer waits"); + assert!(s.script_palette_start().is_none()); +} + +#[test] +fn an_erroring_handler_ends_its_run_and_leaves_the_palette_open() { + let mut s = one_doc(); + let before = s.documents()[0].history.undo.len(); + run( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); throw new Error('broken'); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("broken"), "{e}"); + assert_eq!(s.documents()[0].history.undo.len(), before, "the failed handler's rectangle was rolled back"); + assert_eq!(only_palette(&s), id); +} + +#[test] +fn a_dialog_in_a_handler_throws_in_the_app() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { try { confirm('Sure?'); } catch (e) { vc.log('confirm'); } \ + try { var d = new Window('dialog'); d.add('button', undefined, 'OK'); d.show(); } catch (e) { vc.log('dialog'); } }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("no dialog waits").unwrap()["log"], json!(["confirm", "dialog"])); + assert_eq!(only_palette(&s), id); +} + +#[test] +fn a_handler_with_nobody_to_ask_ends_at_its_dialog() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); p.add('button', undefined, 'Go').onClick = function () { alert('hi'); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("no answer left"), "{e}"); + assert_eq!(only_palette(&s), id, "the palette stays open"); +} + +#[test] +fn palettes_and_waiting_events_have_limits() { + let mut s = one_doc(); + let r = run( + &mut s, + "#targetengine many\nfor (var i = 0; i < 40; i++) { try { new Window('palette').show(); } catch (e) { vc.log([i, e.name]); break; } }", + ) + .unwrap(); + assert_eq!(r["log"], json!([[MAX_PALETTES, "RangeError"]])); + s.execute("script.engine.drop", &json!({"name": "many"})).unwrap(); + assert!(s.script_palettes().is_empty()); + + run_in_app( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); for (var i = 0; i < 70; i++) p.add('button', undefined, 'B' + i); p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + for c in 1..=MAX_WAITING { + assert_eq!(s.script_palette_event(id, UiEvent::Click(c)), Ok(Waiting::Added)); + } + let e = s.script_palette_event(id, UiEvent::Click(MAX_WAITING + 1)).unwrap_err(); + assert!(e.contains("this one was not kept"), "{e}"); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Merged), "a waiting control still takes a click"); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 800b0f35df..08badaae56 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -44,7 +44,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// change anything outside it. const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder Window alert confirm localize prompt toSource"), - ("Window.", "length prototype"), + ("Window.", "__vcPaletteEvent length prototype"), ("Window.prototype.", "add center close constructor findElement hide show"), ("Object.prototype.", "toSource"), ("localize.", "length"), diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index ad8d10acce..117ae759b6 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -502,6 +502,16 @@ impl Realm { } } + /// Gives the host's `paletteUpdate` the controls of each ScriptUI palette this realm keeps, as + /// the run that just ended left them; nothing when it keeps none. A getter it reads runs in the + /// run's fuel, and what it throws ends the run. + pub fn refresh_script_ui(&mut self) -> Result<(), RunError> { + match crate::scriptui::refresh(&mut self.interp) { + 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 index f2f8a33b2c..52f42ee49c 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -2,10 +2,11 @@ //! 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`, +//! `new Window("dialog"[, title, bounds, properties])` makes a dialog, with or without `new`, and +//! `new Window("palette", ...)` a palette, once the host's `palette` allows it. A window of type +//! `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 palette, 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 @@ -24,6 +25,15 @@ //! can be shown while one is. When `show()` ends, the host's `end` is given its result and whether //! it ended normally. //! +//! A palette's `show()` gives the host's `paletteShow` its description and its id (none the first +//! time), which gives back the id, then runs `onShow` and returns `undefined` without waiting. +//! `hide()` gives `paletteHide` the id, and `close()` runs `onClose`, and unless it returns `false` +//! gives `paletteClose` the id; a `close()` while `onClose` runs does nothing more. The realm keeps +//! each palette the host shows until it closes. `Window.__vcPaletteEvent()` takes an event from the +//! host's `paletteEvent` (`{palette, event, id, value}`, or `null`), gives it to that palette as a +//! dialog takes one, and then gives `paletteUpdate` each palette's description; `add()` on a shown +//! palette does the same for that palette, so the host's list of its controls stays in step. +//! //! 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`] @@ -66,8 +76,14 @@ const CLOSING: &str = "__vcClosing"; const ITEMS: &str = "__vcItems"; const SELECTION: &str = "__vcSelection"; const LIST: &str = "__vcList"; +const PALETTE_ID: &str = "__vcPaletteId"; +const IN_CLOSE: &str = "__vcInClose"; +/// How many times a list's items were added or removed: a palette's waiting change of the list is +/// for the items it had then. +const REVISION: &str = "__vcRevision"; -/// The objects of `Window`, kept by the realm, and the dialog that is showing. +/// The objects of `Window`, kept by the realm, the dialog that is showing, and the palettes the +/// host shows, shown or hidden. #[derive(Clone, Debug)] pub(crate) struct Classes { window_proto: ObjId, @@ -78,6 +94,7 @@ pub(crate) struct Classes { selection_get: ObjId, selection_set: ObjId, showing: Option, + palettes: Vec, } impl Classes { @@ -85,10 +102,21 @@ impl Classes { 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.extend(self.palettes.iter().copied()); all } } +/// Is `kind` a window's: a dialog's or a palette's? +fn is_window(kind: &str) -> bool { + kind == "dialog" || kind == "palette" +} + +/// Does `kind` hold controls? +fn is_container(kind: &str) -> bool { + is_window(kind) || kind == "group" || kind == "panel" +} + /// 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() { @@ -254,7 +282,7 @@ fn new_element( set_open(i, o, "bounds", bounds.clone())?; } set_open(i, o, "layout", Value::Object(layout))?; - if matches!(kind, "dialog" | "group" | "panel") { + if is_container(kind) { let kids = list(i, &[], false)?; set_slot(i, o, KIDS, Value::Object(kids))?; let children = list(i, &[], true)?; @@ -274,16 +302,24 @@ fn window_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult if ty.to_lowercase() != "item" { return Err(error(i, "add: a list holds only items")); } - return add_item(i, o, &arg(args, 1)); + let item = add_item(i, o, &arg(args, 1))?; + if let Some(win) = object_slot(i, o, WINDOW)? { + i.rooted(std::slice::from_ref(&item), |i| update_palette(i, win))?; + } + return Ok(item); } - if !matches!(kind.as_str(), "dialog" | "group" | "panel") { + if !is_container(&kind) { return Err(error(i, &format!("add: a {kind} holds no controls"))); } if ty.contains('{') { @@ -401,6 +441,9 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult append(i, o, KIDS, "children", Value::Object(c))?; set_slot(i, win, COUNT, Value::Number(count + 1.0))?; set_slot(i, win, ITEM_COUNT, Value::Number(items + staged as f64))?; + // The host's copy of a shown palette keeps each control's place in the list, which events + // name it by. + update_palette(i, win)?; Ok(Value::Object(c)) })(); i.temp_roots.truncate(mark); @@ -433,6 +476,7 @@ fn new_item(i: &mut Interp, o: ObjId, text: Value) -> JsResult { set_slot(i, item, LIST, Value::Object(o))?; set_open(i, item, "text", text.clone())?; append(i, o, ITEMS, "items", Value::Object(item))?; + bump_revision(i, o)?; Ok(Value::Object(item)) }) }) @@ -530,9 +574,16 @@ fn remove_all(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult JsResult<()> { + let r = number_slot(i, o, REVISION)?; + set_slot(i, o, REVISION, Value::Number(r + 1.0)) +} + fn kids_of(i: &Interp, o: ObjId) -> JsResult> { match object_slot(i, o, KIDS)? { Some(a) => list_values(i, a), @@ -597,29 +648,158 @@ fn nothing(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { Ok(Value::Undefined) } -fn dialog_of(i: &mut Interp, this: &Value, what: &str) -> JsResult { +/// `this` as a window, and whether it is a palette. +fn window_of(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, bool)> { match kind_of(i, this)? { - Some((o, kind)) if kind == "dialog" => Ok(o), + Some((o, kind)) if is_window(&kind) => Ok((o, kind == "palette")), _ => 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. +/// `close([result])`: closes the dialog that is showing once the running handler returns, or the +/// palette at once. fn close(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let o = dialog_of(i, &this, "close")?; + let (o, palette) = window_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) { + if palette { + close_palette(i, o)?; + } else 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. +/// `hide()`: closes the dialog that is showing with the result 0, or hides the palette, which a +/// later `show()` shows again as it was. fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - close(i, this, &[], false) + let (o, palette) = window_of(i, &this, "hide")?; + if !palette { + return close(i, this, &[], false); + } + if let Value::Number(id) = slot(i, o, PALETTE_ID)? { + let f = host_fn(i, "paletteHide")?; + i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + } + Ok(Value::Undefined) +} + +fn set_palettes(i: &mut Interp, f: impl FnOnce(&mut Vec)) { + if let Some(c) = i.script_ui.as_mut() { + f(&mut c.palettes); + } +} + +/// Closes the palette `win` once its `onClose` allows it: the host no longer shows it and its +/// handlers no longer run. A `close()` while its `onClose` runs does nothing more. +fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { + if slot(i, win, IN_CLOSE)?.truthy() { + return Ok(()); + } + set_slot(i, win, IN_CLOSE, Value::Bool(true))?; + let allowed = may_close(i, win); + set_slot(i, win, IN_CLOSE, Value::Undefined)?; + if !allowed? { + return Ok(()); + } + if let Value::Number(id) = slot(i, win, PALETTE_ID)? { + set_slot(i, win, PALETTE_ID, Value::Undefined)?; + set_palettes(i, |p| p.retain(|o| *o != win)); + let f = host_fn(i, "paletteClose")?; + i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + } + Ok(()) +} + +/// Gives the host the controls of the palette `win` as they are now, when it shows the palette. +fn update_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { + let Value::Number(id) = slot(i, win, PALETTE_ID)? else { return Ok(()) }; + let (desc, ..) = describe(i, win)?; + let f = host_fn(i, "paletteUpdate")?; + i.rooted(std::slice::from_ref(&desc), |i| i.call(&f, &Value::Undefined, &[desc.clone(), Value::Number(id)]))?; + Ok(()) +} + +/// Gives the host the controls of every palette it shows, after a handler may have changed them. +fn update_palettes(i: &mut Interp) -> JsResult<()> { + for win in classes(i)?.palettes { + update_palette(i, win)?; + } + Ok(()) +} + +/// Gives the host the controls of every palette the realm keeps, as a run left them +/// ([`crate::Realm::refresh_script_ui`]); nothing without palettes. +pub(crate) fn refresh(i: &mut Interp) -> JsResult<()> { + if i.script_ui.as_ref().is_none_or(|c| c.palettes.is_empty()) { + return Ok(()); + } + update_palettes(i) +} + +/// A palette's `show()`: the host shows its description at once, then `onShow` runs, and `show()` +/// returns `undefined` without waiting. +fn show_palette(i: &mut Interp, win: ObjId) -> JsResult { + let (desc, ..) = describe(i, win)?; + let id = slot(i, win, PALETTE_ID)?; + let f = host_fn(i, "paletteShow")?; + Ok(Pause { host: f, args: vec![desc, id], keep: vec![Value::Object(win)], resume: palette_shown, failed: None }) +} + +fn palette_shown(i: &mut Interp, keep: &[Value], id: Value) -> JsResult { + let Some(win) = arg(keep, 0).as_object() else { return Err(Abrupt::Internal("show lost its palette".into())) }; + let Value::Number(_) = id else { return Err(Abrupt::Internal("the host gave the palette no id".into())) }; + set_slot(i, win, PALETTE_ID, id)?; + if !classes(i)?.palettes.contains(&win) { + set_palettes(i, |p| p.push(win)); + } + handler(i, win, "onShow")?; + update_palette(i, win)?; + Ok(Value::Undefined) +} + +/// `Window.__vcPaletteEvent()`, which the run of a palette's handler calls: takes the event from the +/// host's `paletteEvent`, gives it to the palette the way a dialog takes the person's event, and +/// gives the host every palette's controls afterward. An event for a palette that has closed does +/// nothing. +fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + let f = host_fn(i, "paletteEvent")?; + let answer = i.call(&f, &Value::Undefined, &[])?; + let Some(ev) = answer.as_object() else { return Ok(Value::Undefined) }; + let mark = i.temp_roots.len(); + i.temp_roots.push(answer.clone()); + let r = (|| { + let id = slot(i, ev, "palette")?; + let palettes = classes(i)?.palettes; + let mut win = None; + for p in palettes { + if matches!((slot(i, p, PALETTE_ID)?, &id), (Value::Number(a), Value::Number(b)) if a == *b) { + win = Some(p); + } + } + let Some(win) = win else { return Ok(Value::Undefined) }; + let event = match slot(i, ev, "event")? { + Value::String(s) => s.to_rust_string(), + _ => String::new(), + }; + if event == "close" { + close_palette(i, win)?; + } else { + let (_, nodes, ..) = describe(i, win)?; + i.temp_roots.push(Value::Object(nodes)); + let count = list_values(i, nodes)?.len(); + if !matches!(slot(i, ev, "id")?, Value::Number(n) if n >= 1.0 && n.fract() == 0.0 && (n as usize) < count) { + return Err(error(i, "a palette event names a control the palette no longer holds")); + } + take_event(i, win, nodes, ev, &event, None)?; + } + update_palettes(i)?; + Ok(Value::Undefined) + })(); + i.temp_roots.truncate(mark); + r } fn host_fn(i: &mut Interp, name: &str) -> JsResult { @@ -633,9 +813,13 @@ fn set_showing(i: &mut Interp, showing: Option) { } } -/// `show()` on a dialog: gives its description to the host's `open`, then runs it ([`opened`]). +/// `show()` on a dialog: gives its description to the host's `open`, then runs it ([`opened`]). On a +/// palette: [`show_palette`]. fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult { - let win = dialog_of(i, &this, "show")?; + let (win, palette) = window_of(i, &this, "show")?; + if palette { + return show_palette(i, win); + } 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")), @@ -745,75 +929,123 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { } 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, - }; - // The index is into the items the person saw. - let shown = match arg(keep, 4).as_object() { - Some(lists) => list_values(i, lists)?.get(id).cloned().unwrap_or(Value::Undefined), - None => Value::Undefined, - }; - if !same(&slot(i, c, ITEMS)?, &shown) { - return Err(error(i, "show: a list's items changed before the person's choice was taken")); - } - set_slot(i, c, SELECTION, Value::Number(n))?; - } - } - handler(i, c, "onChange")?; - } - _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), - } + take_event(i, win, nodes, ev, &event, Some(keep))?; next(i, win) }) } +/// A click or a change the host gave in `ev` for control `id` of `nodes` (a description's list of +/// elements): the control takes it and its handler runs. A dialog's button without `onClick` asks +/// to close it with 1 when it is the default element and 2 when it is the cancel element, which +/// `keep` (`show()`'s kept values) names; a palette has no `keep`. +fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, keep: Option<&[Value]>) -> JsResult<()> { + 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 { + "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 Some(keep) = keep + { + 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, + }; + match keep { + // The index is into the items the person saw. + Some(keep) => { + let shown = match arg(keep, 4).as_object() { + Some(lists) => list_values(i, lists)?.get(id).cloned().unwrap_or(Value::Undefined), + None => Value::Undefined, + }; + if !same(&slot(i, c, ITEMS)?, &shown) { + return Err(error(i, "show: a list's items changed before the person's choice was taken")); + } + } + // A palette's list may have changed while the event waited: the host gives + // the items the person saw and the list's revision then. + None => { + let revised = match slot(i, ev, "revision")? { + Value::Number(r) => r != number_slot(i, c, REVISION)?, + _ => false, + }; + if revised || !same_items(i, c, &slot(i, ev, "items")?)? || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { + return Err(error(i, "a palette's list changed before the person's choice was taken")); + } + } + } + set_slot(i, c, SELECTION, Value::Number(n))?; + } + } + handler(i, c, "onChange")?; + } + _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), + } + Ok(()) +} + +/// Does the list `c` hold items with the texts in `seen` (an array of strings), in that order? True +/// when `seen` is not an array. +fn same_items(i: &mut Interp, c: ObjId, seen: &Value) -> JsResult { + let Some(seen) = seen.as_object() else { return Ok(true) }; + let seen = list_values(i, seen)?; + let items = items_of(i, c)?; + if seen.len() != items.len() { + return Ok(false); + } + i.rooted(&items, |i| { + for (item, want) in items.iter().zip(&seen) { + let Some(item) = item.as_object() else { return Ok(false) }; + let text = get(i, item, "text")?; + if i.to_str(&text)?.to_rust_string() != i.to_str(want)?.to_rust_string() { + return Ok(false); + } + } + Ok(true) + }) +} + 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()) }; @@ -963,8 +1195,10 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { 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")?; + // A palette is described as a dialog is; the host knows which it shows. + let shown_kind = if kind == "palette" { "dialog" } else { kind.as_str() }; let mut d: Vec<(String, Data)> = vec![ - ("kind".into(), Data::String(kind.clone())), + ("kind".into(), Data::String(shown_kind.to_string())), ("parent".into(), Data::Number(*parent)), ("name".into(), Data::String(name.clone())), ("text".into(), Data::String(text.clone())), @@ -981,7 +1215,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { d.push(("size".into(), numbers(i, &size, &["width", "height"], "preferredSize")?)); let a = get_kept(i, o, "alignment")?; d.push(("alignment".into(), alignment(i, &a)?)); - if matches!(kind.as_str(), "dialog" | "group" | "panel") { + if is_container(kind) { let orientation = get(i, o, "orientation")?; d.push(("orientation".into(), Data::String(text_of(i, &orientation, "an orientation")?.to_lowercase()))); let ac = get_kept(i, o, "alignChildren")?; @@ -1026,6 +1260,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { 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)))); + d.push(("revision".into(), Data::Number(number_slot(i, o, REVISION)?))); } _ => {} } @@ -1079,9 +1314,21 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul 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 }); + i.script_ui = Some(Classes { + window_proto, + control_proto, + item_proto, + layout, + host, + selection_get, + selection_set, + showing: None, + palettes: Vec::new(), + }); let window = native(i, "Window", window_ctor, 4, NativeKind::Plain, true)?; constructor(i, "Window", window, window_proto)?; + let event = native(i, "__vcPaletteEvent", palette_event, 0, NativeKind::Plain, false)?; + i.define(window, key("__vcPaletteEvent"), Prop::Data { value: Value::Object(event), flags: 0 })?; method(i, window_proto, "add", add, 4)?; method(i, window_proto, "findElement", find_element, 1)?; method(i, window_proto, "close", close, 1)?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 7d0d8376a3..76a70d331d 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -232,7 +232,8 @@ fn a_dialog_can_be_shown_again_after_it_closed() { #[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('window')", "Window: a window of type window is not available yet; use dialog or palette"), + ("new Window('palette')", "Window: this host shows no palettes"), ("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"), @@ -373,6 +374,129 @@ fn a_show_that_waits_resumes_with_the_host_s_answer() { assert_eq!(seen.borrow().ends, vec![(1.0, true)]); } +/// What a palette host was asked: each call's name and its palette id (0 for none). +type Calls = Rc>>; + +/// A realm with palette host functions: `paletteShow` gives ids from 1, and `paletteEvent` gives +/// the events in `events`, in order, then `null`. +fn palette_realm(events: Vec) -> (Realm, Calls) { + let mut r = Realm::new(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + let calls: Calls = Rc::default(); + let events = Rc::new(RefCell::new(VecDeque::from(events))); + let id_of = |args: &[Data], at: usize| match args.get(at) { + Some(Data::Number(n)) => *n, + _ => 0.0, + }; + let record = |name: &'static str, at: usize| -> HostFunction { + let c = calls.clone(); + Rc::new(move |args| { + c.borrow_mut().push((name.to_string(), id_of(&args, at))); + Ok(Data::Undefined) + }) + }; + let c = calls.clone(); + let show: HostFunction = Rc::new(move |args| { + let given = id_of(&args, 1); + let id = if given > 0.0 { given } else { 1.0 + c.borrow().iter().filter(|(n, _)| n == "paletteShow").count() as f64 }; + c.borrow_mut().push(("paletteShow".into(), id)); + Ok(Data::Number(id)) + }); + let event: HostFunction = Rc::new(move |_| Ok(events.borrow_mut().pop_front().unwrap_or(Data::Null))); + let none: HostFunction = Rc::new(|_| Err(HostError::Error("no dialog here".into()))); + let items = vec![ + ("open".into(), HostItem::Function(none.clone())), + ("wait".into(), HostItem::Function(none.clone())), + ("end".into(), HostItem::Function(none)), + ("palette".into(), HostItem::Function(record("palette", 0))), + ("paletteShow".into(), HostItem::Function(show)), + ("paletteUpdate".into(), HostItem::Function(record("paletteUpdate", 1))), + ("paletteHide".into(), HostItem::Function(record("paletteHide", 0))), + ("paletteClose".into(), HostItem::Function(record("paletteClose", 0))), + ("paletteEvent".into(), HostItem::Function(event)), + ]; + r.define_script_ui(items).unwrap(); + (r, calls) +} + +fn palette_event(palette: f64, event: Data) -> Data { + let Data::Object(mut fields) = event else { return Data::Null }; + fields.push(("palette".into(), Data::Number(palette))); + Data::Object(fields) +} + +fn names(calls: &Calls) -> Vec { + calls.borrow().iter().map(|(n, _)| n.clone()).collect() +} + +#[test] +fn a_palette_s_show_returns_at_once_and_its_events_run_its_handlers() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(2)), palette_event(1.0, change(3, Data::String("typed".into())))]); + let made = r + .run( + "var p = new Window('palette', 'Tools'); var label = p.add('statictext', undefined, 'idle'); \ + var b = p.add('button', undefined, 'Go'); var t = p.add('edittext', undefined, ''); var log = []; \ + b.onClick = function () { log.push('click'); label.text = 'clicked'; }; \ + t.onChange = function () { log.push('change ' + t.text); }; String(p.show())", + ) + .unwrap(); + assert_eq!(made, JsValue::String("undefined".into()), "show() gives undefined without waiting"); + assert_eq!(names(&calls), ["palette", "paletteShow", "paletteUpdate"]); + r.run("Window.__vcPaletteEvent(); Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("log.join('|') + '|' + label.text").unwrap(), JsValue::String("click|change typed|clicked".into())); + assert_eq!(calls.borrow().iter().filter(|(n, id)| n == "paletteUpdate" && *id == 1.0).count(), 3, "each event gives the host the new controls"); + assert_eq!(r.run("Window.__vcPaletteEvent(); 'nothing'").unwrap(), JsValue::String("nothing".into()), "no event left: nothing runs"); +} + +#[test] +fn closing_a_palette_runs_on_close_which_can_keep_it_open() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, close()), palette_event(1.0, close()), palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; b.onClick = function () { clicks++; }; \ + var asked = 0; p.onClose = function () { asked++; p.close(); return asked > 1; }; p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert!(!names(&calls).contains(&"paletteClose".to_string()), "the first onClose kept it open"); + r.run("Window.__vcPaletteEvent(); Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("[asked, clicks].join()").unwrap(), JsValue::String("2,0".into()), "a close inside onClose does not run it again"); + assert_eq!(calls.borrow().iter().filter(|(n, _)| n == "paletteClose").count(), 1); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); +} + +#[test] +fn a_palette_list_change_after_its_items_changed_throws() { + let seen = |index: f64| { + let Data::Object(mut fields) = palette_event(1.0, change(1, Data::Number(index))) else { return Data::Null }; + fields.push(("items".into(), Data::Array(vec![Data::String("a".into()), Data::String("b".into())]))); + // The two items the list was made with. + fields.push(("revision".into(), Data::Number(2.0))); + Data::Object(fields) + }; + let (mut r, _) = palette_realm(vec![seen(1.0), seen(1.0), seen(1.0), seen(1.0)]); + r.run("var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; l.onChange = function () { got.push(String(l.selection)); }; p.show();") + .unwrap(); + r.run("Window.__vcPaletteEvent(); l.removeAll(); l.add('item', 'c'); l.add('item', 'd');").unwrap(); + let message = "a palette's list changed before the person's choice was taken"; + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String(message.into()), "the same number of items, other texts"); + r.run("l.removeAll(); l.add('item', 'a');").unwrap(); + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String(message.into()), "fewer items"); + r.run("l.removeAll(); l.add('item', 'a'); l.add('item', 'b');").unwrap(); + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String(message.into()), "new items with the same texts"); + assert_eq!(r.run("got.join()").unwrap(), JsValue::String("b".into())); +} + +#[test] +fn hide_keeps_the_palette_and_show_shows_it_again_with_the_same_id() { + let (mut r, calls) = palette_realm(Vec::new()); + r.run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); p.hide(); p.show();").unwrap(); + let shows: Vec = calls.borrow().iter().filter(|(n, _)| n == "paletteShow" || n == "paletteHide").map(|(_, id)| *id).collect(); + assert_eq!(shows, [1.0, 1.0, 1.0]); +} + #[test] fn findelement_items_and_selection_follow_the_list() { let (mut r, _, _) = realm(Vec::new()); diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 0045c764f2..9854310ff5 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -179,7 +179,7 @@ features! { Reflection "reflection" HostOnly, ScriptuiDialog "scriptui.dialog" Dialogs, ScriptuiDrawing "scriptui.drawing" Dialogs, - ScriptuiPalette "scriptui.palette" HostOnly, + ScriptuiPalette "scriptui.palette" Dialogs, ScriptuiWindow "scriptui.window" Dialogs, SelectTool "selectTool" HostOnly, Socket "socket" HostOnly, diff --git a/crates/scriptcheck/src/lib.rs b/crates/scriptcheck/src/lib.rs index 2bd8c60fba..c0d626c998 100644 --- a/crates/scriptcheck/src/lib.rs +++ b/crates/scriptcheck/src/lib.rs @@ -119,8 +119,8 @@ pub enum Need { MenuCommands, /// Dialogs and windows of its own. Dialogs, - /// Features only the reference app has (palettes, messages to other apps, network - /// connections, native code, E4X, actions). + /// Features only the reference app has (messages to other apps, network connections, native + /// code, E4X, actions). HostOnly, } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index b771cc6417..8b216bcc48 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -1369,6 +1369,12 @@ fn declarations_past_a_limit_hold_from_where_they_stand() { assert_eq!(notify(five, &Limits::default()).0, Vec::::new()); } +#[test] +fn palettes_need_dialogs() { + let r = report("#targetengine tools\nvar w = new Window('palette');\nw.show();\n"); + assert_eq!(r.needs, [Need::Language, Need::Dialogs]); +} + #[test] fn application_methods_are_features_not_members() { let r = report("app.executeMenuCommand('acmecopyall');\napp.selectTool('acme');\n"); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..bd2bba2159 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -368,6 +368,11 @@ impl VectorcraftApp { crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); crate::dialogs::proof_setup::poll(self, ctx); + // A palette event whose run starts on the next frame. While a run goes on, the block below + // asks for its frames, and a run that waits for the person goes on at their next input. + if self.session.script_palette_events_waiting() > 0 && !self.session.script_running() { + ctx.request_repaint(); + } if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() @@ -638,6 +643,7 @@ impl VectorcraftApp { egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.pasteboard)).show(ui, |ui| panel_docking::show(self, ui)); panels::learn::locate::tidy(self, &ctx); crate::doc_windows::show(self, &ctx); + crate::script_palettes::show(self, &ctx); dialogs::show(self, &ctx); updates_ui::show(self, &ctx); export_progress::show(self, &ctx); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 158a86ea5b..9aea178b9a 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -215,7 +215,13 @@ pub(crate) fn prompt_of(w: &ScriptUiDialog, i: usize) -> &str { /// Draws control `i` (`n`, with the prompt [`prompt_of`] gives) at its place from `origin`. → the /// event it gives. -fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, (i, n, prompt): (usize, &UiNode, &str), default: bool) -> Option { +pub(crate) fn control( + ui: &mut egui::Ui, + d: &mut Dialog, + origin: egui::Pos2, + (i, n, prompt): (usize, &UiNode, &str), + 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; diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 9d442848ce..51a518f798 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6582,6 +6582,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg there is no script engine named {name} no hi ha cap motor d'scripts anomenat {name} @msg `answers` must be a list of answers `answers` ha de ser una llista de respostes @msg `answers` has more than {MAX_ANSWERS} answers `answers` té més de {MAX_ANSWERS} respostes +@msg {MAX_WAITING} script palette events already wait; this one was not kept ja esperen {MAX_WAITING} esdeveniments de paletes d'scripts; aquest no s'ha conservat @msg `answers` is larger than 1 MiB `answers` ocupa més d'1 MiB @msg must be an object with `kind` and `value` ha de ser un objecte amb `kind` i `value` @msg must have exactly `kind` and `value` ha de tenir exactament `kind` i `value` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ee8b68af7d..9457178baf 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8986,6 +8986,7 @@ breakText Glyphs Glyfy @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` musí uvádět indexy kotevních bodů (0, 1, 2…), ne {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` pro tento dialog {kind} musí být jedna z hodnot: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` má více než {MAX_ANSWERS} odpovědí +@msg {MAX_WAITING} script palette events already wait; this one was not kept už čeká {MAX_WAITING} událostí palet skriptů; tato nebyla zachována @msg `answers` is larger than 1 MiB `answers` je větší než 1 MiB @msg `answers` must be a list of answers `answers` musí být seznam odpovědí @msg `artboard` must be the index of an artboard of the document `artboard` musí být index pracovní plochy dokumentu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index cc03e6ef1b..1ef0d2169d 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -225,6 +225,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg there is no script engine named {name} der findes ingen scriptmotor med navnet {name} @msg `answers` must be a list of answers `answers` skal være en liste med svar @msg `answers` has more than {MAX_ANSWERS} answers `answers` har flere end {MAX_ANSWERS} svar +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} hændelser fra scriptpaletter venter allerede; denne blev ikke gemt @msg `answers` is larger than 1 MiB `answers` er større end 1 MiB @msg `answers[{i}]` {e} `answers[{i}]` {e} @msg must be an object with `kind` and `value` skal være et objekt med `kind` og `value` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index e92726501f..935a135c4b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8426,6 +8426,7 @@ breakText Glyphs Glyphen @msg `align` must be a string `align` muss ein String sein @msg `answer` for this {kind} dialog must be one of: {_1} `answer` für dieses {kind}-Dialogfeld muss eines der folgenden sein: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` hat mehr als {MAX_ANSWERS} Antworten +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} Ereignisse von Skriptpaletten warten bereits; dieses wurde nicht behalten @msg `answers` is larger than 1 MiB `answers` ist größer als 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` ist nur für einen Lauf ohne jemanden, der gefragt werden kann: In der App beantwortet die Person jeden Dialog @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` muss eine ganze Zahl von 1 bis {_1} sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 12d3aba3c5..aa30a34709 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2779,6 +2779,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg there is no script engine named {name} δεν υπάρχει μηχανή σεναρίων με όνομα {name} @msg `answers` must be a list of answers το `answers` πρέπει να είναι λίστα απαντήσεων @msg `answers` has more than {MAX_ANSWERS} answers το `answers` έχει περισσότερες από {MAX_ANSWERS} απαντήσεις +@msg {MAX_WAITING} script palette events already wait; this one was not kept ήδη περιμένουν {MAX_WAITING} συμβάντα παλετών σεναρίων· αυτό δεν κρατήθηκε @msg `answers` is larger than 1 MiB το `answers` είναι μεγαλύτερο από 1 MiB @msg `answers[{i}]` {e} το `answers[{i}]` {e} @msg must be an object with `kind` and `value` πρέπει να είναι αντικείμενο με `kind` και `value` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c404d6ed6e..5cc8d86fdf 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5054,6 +5054,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg there is no script engine named {name} no hay ningún motor de scripts llamado {name} @msg `answers` must be a list of answers `answers` debe ser una lista de respuestas @msg `answers` has more than {MAX_ANSWERS} answers `answers` tiene más de {MAX_ANSWERS} respuestas +@msg {MAX_WAITING} script palette events already wait; this one was not kept ya esperan {MAX_WAITING} eventos de paletas de scripts; este no se ha conservado @msg `answers` is larger than 1 MiB `answers` ocupa más de 1 MiB @msg must be an object with `kind` and `value` debe ser un objeto con `kind` y `value` @msg must have exactly `kind` and `value` debe tener exactamente `kind` y `value` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 2ae421c004..1205c1dc9d 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5295,6 +5295,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg there is no script engine named {name} skriptimoottoria nimeltä {name} ei ole @msg `answers` must be a list of answers `answers` on oltava vastausten luettelo @msg `answers` has more than {MAX_ANSWERS} answers kohteessa `answers` on yli {MAX_ANSWERS} vastausta +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} skriptipalettien tapahtumaa odottaa jo; tätä ei säilytetty @msg `answers` is larger than 1 MiB `answers` on suurempi kuin 1 MiB @msg must be an object with `kind` and `value` on oltava objekti, jossa on `kind` ja `value` @msg must have exactly `kind` and `value` siinä on oltava täsmälleen `kind` ja `value` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index aa2a24c90d..dbdca9ca76 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8853,6 +8853,7 @@ breakText Glyphs Glyphes @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` doit lister des indices de points d’ancrage (0, 1, 2…), pas {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` pour cette boîte de dialogue {kind} doit valoir l’une de ces valeurs : {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` contient plus de {MAX_ANSWERS} réponses +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} événements de palettes de script attendent déjà, celui-ci n’a donc pas été conservé @msg `answers` is larger than 1 MiB `answers` dépasse 1 Mio @msg `answers` must be a list of answers `answers` doit être une liste de réponses @msg `artboard` must be the index of an artboard of the document `artboard` doit être l’indice d’un plan de travail du document diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 5bdc231564..8c5e1f5602 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7728,6 +7728,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg there is no script engine named {name} {name} नाम का कोई स्क्रिप्ट इंजन नहीं है @msg `answers` must be a list of answers `answers` उत्तरों की सूची होनी चाहिए @msg `answers` has more than {MAX_ANSWERS} answers `answers` में {MAX_ANSWERS} से अधिक उत्तर हैं +@msg {MAX_WAITING} script palette events already wait; this one was not kept स्क्रिप्ट पैलेट की {MAX_WAITING} घटनाएँ पहले से प्रतीक्षा में हैं; यह नहीं रखी गई @msg `answers` is larger than 1 MiB `answers` 1 MiB से बड़ा है @msg `answers[{i}]` {e} `answers[{i}]`: {e} @msg must be an object with `kind` and `value` `kind` और `value` वाला ऑब्जेक्ट होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index af96effe62..6f7ce5a4ca 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8857,6 +8857,7 @@ breakText Glyphs Glifák @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors`: horgonypont-indexek listája kell (0, 1, 2…), ez nem az: {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer`: ennél a párbeszédablaknál ({kind}) ezek egyike kell: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers`: több mint {MAX_ANSWERS} választ tartalmaz +@msg {MAX_WAITING} script palette events already wait; this one was not kept már {MAX_WAITING} parancsfájlpaletta-esemény várakozik; ez nem lett megtartva @msg `answers` is larger than 1 MiB `answers`: nagyobb 1 MiB-nál @msg `answers` must be a list of answers `answers`: válaszok listája kell @msg `artboard` must be the index of an artboard of the document `artboard`: a dokumentum egyik rajztáblájának indexe kell diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 87d73912db..25e340bec0 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -133,6 +133,7 @@ @msg {name}: `answers` has no answer left for this dialog {name}: `answers` tidak memiliki jawaban tersisa untuk dialog ini @msg `answers` must be a list of answers `answers` harus berupa daftar jawaban @msg `answers` has more than {MAX_ANSWERS} answers `answers` berisi lebih dari {MAX_ANSWERS} jawaban +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} peristiwa palet skrip sudah menunggu; yang ini tidak disimpan @msg `answers` is larger than 1 MiB `answers` lebih besar dari 1 MiB @msg must be an object with `kind` and `value` harus berupa objek dengan `kind` dan `value` @msg must have exactly `kind` and `value` harus memiliki tepat `kind` dan `value` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5aab7c3e3d..ea73cf2b91 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8467,6 +8467,7 @@ breakText Glyphs Glifi @msg `align` must be a string `align` deve essere una stringa @msg `answer` for this {kind} dialog must be one of: {_1} `answer` per questa finestra di dialogo {kind} deve essere uno tra: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` ha più di {MAX_ANSWERS} risposte +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} eventi delle palette di script sono già in attesa; questo non è stato conservato @msg `answers` is larger than 1 MiB `answers` supera 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` è solo per un'esecuzione senza nessuno a cui chiedere: nell'app, la persona risponde a ogni finestra di dialogo @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` deve essere un numero intero da 1 a {_1} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ef0740a8bb..0b73565e9a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7293,6 +7293,7 @@ axis Y Axis Y 軸 @msg `align` must be a string `align` には文字列を指定してください @msg `answer` for this {kind} dialog must be one of: {_1} この {kind} ダイアログの `answer` には次のいずれかを指定してください: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` の回答が {MAX_ANSWERS} 個を超えています +@msg {MAX_WAITING} script palette events already wait; this one was not kept スクリプトパレットのイベントがすでに {MAX_WAITING} 件待機しているため、このイベントは保持されませんでした @msg `answers` is larger than 1 MiB `answers` が 1 MiB を超えています @msg `answers` must be a list of answers `answers` には回答のリストを指定してください @msg `artboard` must be the index of an artboard of the document `artboard` にはドキュメントのアートボードのインデックスを指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index e7223c60c8..541d871302 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -176,6 +176,7 @@ @msg `answer` for this {kind} dialog must be one of: {_1} დიალოგისთვის (ტიპი: {kind}) `answer` უნდა იყოს ერთ-ერთი: {_1} @msg `answers[{i}]` {e} `answers[{i}]` {e} @msg `answers` has more than {MAX_ANSWERS} answers `answers` შეიცავს {MAX_ANSWERS}-ზე მეტ პასუხს +@msg {MAX_WAITING} script palette events already wait; this one was not kept სკრიპტის პალიტრების {MAX_WAITING} მოვლენა უკვე ელოდება; ეს არ შენარჩუნდა @msg `answers` is larger than 1 MiB `answers` 1 MiB-ზე დიდია @msg `answers` must be a list of answers `answers` უნდა იყოს პასუხების სია @msg `artboard` must be the index of an artboard of the document `artboard` უნდა იყოს დოკუმენტის სამუშაო დაფის ინდექსი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e40e7055a2..07bde95166 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8625,6 +8625,7 @@ breakText Glyphs 글리프 @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors`에는 앵커 인덱스(0, 1, 2…)를 나열해야 합니다: {v} @msg `answer` for this {kind} dialog must be one of: {_1} 이 {kind} 대화 상자의 `answer`은(는) 다음 중 하나여야 합니다: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers`에 응답이 {MAX_ANSWERS}개보다 많습니다 +@msg {MAX_WAITING} script palette events already wait; this one was not kept 스크립트 팔레트 이벤트가 이미 {MAX_WAITING}개 대기 중이므로 이 이벤트는 보관되지 않았습니다 @msg `answers` is larger than 1 MiB `answers`이(가) 1 MiB보다 큽니다 @msg `answers` must be a list of answers `answers`은(는) 응답 목록이어야 합니다 @msg `artboard` must be the index of an artboard of the document `artboard`은(는) 문서에 있는 아트보드의 인덱스여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d52992f4a9..9287dd44e3 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6493,6 +6493,7 @@ imageTrace Outline Contour @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` moet ankerindexen bevatten (0, 1, 2…), niet {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` voor dit dialoogvenster {kind} moet een van de volgende zijn: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` heeft meer dan {MAX_ANSWERS} antwoorden +@msg {MAX_WAITING} script palette events already wait; this one was not kept er wachten al {MAX_WAITING} gebeurtenissen van scriptpaletten; deze is niet bewaard @msg `answers` is larger than 1 MiB `answers` is groter dan 1 MiB @msg `answers` must be a list of answers `answers` moet een lijst met antwoorden zijn @msg `artboard` must be the index of an artboard of the document `artboard` moet de index van een tekengebied van het document zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 1a2148f0e1..fd7342da72 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8670,6 +8670,7 @@ breakText Glyphs Glify @msg `align` must be a string `align` musi być ciągiem znaków @msg `answer` for this {kind} dialog must be one of: {_1} `answer` dla tego okna dialogowego {kind} musi mieć jedną z wartości: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` zawiera więcej niż {MAX_ANSWERS} odpowiedzi +@msg {MAX_WAITING} script palette events already wait; this one was not kept czeka już {MAX_WAITING} zdarzeń palet skryptów; to zdarzenie nie zostało zachowane @msg `answers` is larger than 1 MiB `answers` ma rozmiar większy niż 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` służy tylko do uruchomienia, w którym nie ma kogo zapytać: w aplikacji na każde okno dialogowe odpowiada użytkownik @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` musi być liczbą całkowitą od 1 do {_1} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 82cdb0a2b2..4aa2697468 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9039,6 +9039,7 @@ swatch Yellow Green Verde-amarelado @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` deve listar índices de pontos de ancoragem (0, 1, 2…), não {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` para esta caixa de diálogo {kind} deve ser um de: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` tem mais de {MAX_ANSWERS} respostas +@msg {MAX_WAITING} script palette events already wait; this one was not kept já há {MAX_WAITING} eventos de paletas de script aguardando; este não foi mantido @msg `answers` is larger than 1 MiB `answers` tem mais de 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` é só para uma execução sem ninguém a quem perguntar: no app, a pessoa responde a cada caixa de diálogo @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` deve ser um número inteiro de 1 a {_1} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 6f351f1d76..ac74d5747a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5076,6 +5076,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg there is no script engine named {name} движка скриптов с именем {name} нет @msg `answers` must be a list of answers `answers` должен быть списком ответов @msg `answers` has more than {MAX_ANSWERS} answers в `answers` больше {MAX_ANSWERS} ответов +@msg {MAX_WAITING} script palette events already wait; this one was not kept уже ожидают {MAX_WAITING} событий палитр скриптов; это событие не сохранено @msg `answers` is larger than 1 MiB `answers` больше 1 МиБ @msg must be an object with `kind` and `value` должен быть объектом с `kind` и `value` @msg must have exactly `kind` and `value` должен содержать ровно `kind` и `value` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 532e1ade50..dc74ea16ce 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4951,6 +4951,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg there is no script engine named {name} det finns ingen skriptmotor med namnet {name} @msg `answers` must be a list of answers `answers` måste vara en lista med svar @msg `answers` has more than {MAX_ANSWERS} answers `answers` har fler än {MAX_ANSWERS} svar +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} händelser från skriptpaletter väntar redan; den här sparades inte @msg `answers` is larger than 1 MiB `answers` är större än 1 MiB @msg `answers[{i}]` {e} `answers[{i}]` {e} @msg must be an object with `kind` and `value` måste vara ett objekt med `kind` och `value` diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index daba147a6d..955a2662d8 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -5760,6 +5760,39 @@ fn f(p: &Value) -> Result<()> { assert_eq!(source_messages(code, &engine, &consts), ["the name is too long", "`path` is empty"]); } +/// The status a ScriptUI palette's click shows when the line of waiting events is full is +/// translated in every language that translates every message, with the count kept. +#[test] +fn script_palette_line_full_is_translated() { + use serde_json::json; + use vectorcraft_engine::script::UiEvent; + let template = "{MAX_WAITING} script palette events already wait; this one was not kept"; + assert!(message_literals().contains(template)); + let mut s = vectorcraft_engine::Session::new(); + let source = "#targetengine tools\nvar p = new Window('palette'); for (var i = 0; i < 70; i++) p.add('button', undefined, 'B' + i); p.show();"; + s.execute("script.run", &json!({"source": source})).unwrap(); + let id = s.script_palettes()[0].id; + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"source": "confirm('Go?');"})).unwrap()["running"], true); + while s.script_dialog().is_none() { + assert!(s.script_pump().is_none(), "the run waits at its confirm"); + } + let mut full = None; + for c in 1..=70 { + if let Err(e) = s.script_palette_event(id, UiEvent::Click(c)) { + full = Some(e); + break; + } + } + let full = full.expect("the line filled"); + assert_eq!(full, template.replace("{MAX_WAITING}", "64")); + for code in COMPLETE_MESSAGES { + let shown = message(Lang::from_code(code).expect("registered"), &full); + assert_ne!(shown, full, "{code}"); + assert!(shown.contains("64"), "{code}: {shown}"); + } +} + /// `script.run`'s refusals of `answers`, the list's own, an answer's at its index and the refusal /// of `answers` in the app, are translated in every language that translates every message, with /// the index, the counts and the code names kept. The command's error stays in English. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 22568734be..109ef0345a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7669,6 +7669,7 @@ axis Y Axis Y ekseni @msg `align` must be a string `align` bir dize olmalıdır @msg `answer` for this {kind} dialog must be one of: {_1} bu {kind} iletişim kutusu için `answer` şunlardan biri olmalıdır: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` içinde {MAX_ANSWERS} taneden fazla yanıt var +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} betik paleti olayı zaten bekliyor; bu olay tutulmadı @msg `answers` is larger than 1 MiB `answers` 1 MiB'tan büyük @msg `answers` must be a list of answers `answers` bir yanıt listesi olmalıdır @msg `artboard` must be the index of an artboard of the document `artboard`, belgedeki bir çalışma yüzeyinin dizini olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 1c44123d26..20e6a222ab 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8626,6 +8626,7 @@ breakText Glyphs Гліфи @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` має містити індекси опорних точок (0, 1, 2…), а не {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` для цього діалогового вікна ({kind}) має бути одним з: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` містить понад {MAX_ANSWERS} відповідей +@msg {MAX_WAITING} script palette events already wait; this one was not kept уже очікують {MAX_WAITING} подій палітр скриптів; цю подію не збережено @msg `answers` is larger than 1 MiB `answers` більший за 1 МіБ @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} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 2758865931..173c74895c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5575,6 +5575,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg there is no script engine named {name} không có bộ máy tập lệnh nào tên {name} @msg `answers` must be a list of answers `answers` phải là một danh sách câu trả lời @msg `answers` has more than {MAX_ANSWERS} answers `answers` có hơn {MAX_ANSWERS} câu trả lời +@msg {MAX_WAITING} script palette events already wait; this one was not kept đã có {MAX_WAITING} sự kiện bảng tập lệnh đang chờ; sự kiện này không được giữ lại @msg `answers` is larger than 1 MiB `answers` lớn hơn 1 MiB @msg must be an object with `kind` and `value` phải là một đối tượng có `kind` và `value` @msg must have exactly `kind` and `value` phải có đúng `kind` và `value` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index dac4499a58..129b2fff68 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8676,6 +8676,7 @@ breakText Glyphs 字形 @msg `align` must be a string `align` 必须是字符串 @msg `answer` for this {kind} dialog must be one of: {_1} 此 {kind} 对话框的 `answer` 必须是以下之一:{_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` 中的回答超过 {MAX_ANSWERS} 个 +@msg {MAX_WAITING} script palette events already wait; this one was not kept 已有 {MAX_WAITING} 个脚本面板事件在等待;此事件未保留 @msg `answers` is larger than 1 MiB `answers` 大于 1 MiB @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} 之间的整数 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index bf6ee14a81..b11084d879 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8621,6 +8621,7 @@ breakText Glyphs 字符 @msg `align` must be a string `align` 必須是字串 @msg `answer` for this {kind} dialog must be one of: {_1} 此 {kind} 對話框的 `answer` 必須是下列其中之一:{_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` 的答案超過 {MAX_ANSWERS} 個 +@msg {MAX_WAITING} script palette events already wait; this one was not kept 已有 {MAX_WAITING} 個指令碼面板事件在等待;此事件未保留 @msg `answers` is larger than 1 MiB `answers` 大於 1 MiB @msg `answers` must be a list of answers `answers` 必須是答案清單 @msg `artboard` must be the index of an artboard of the document `artboard` 必須是文件中某個工作區域的索引 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a50527cede..5bbfae206c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -70,6 +70,7 @@ pub mod print; pub mod recovery; pub mod render_worker; pub mod screen_color; +pub mod script_palettes; pub mod script_runs; pub mod scripts_menu; mod scrub; diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs new file mode 100644 index 0000000000..125adf0365 --- /dev/null +++ b/crates/ui-egui/src/script_palettes.rs @@ -0,0 +1,93 @@ +//! The ScriptUI palettes a script shows with `new Window("palette")` in a named engine +//! ([`vectorcraft_engine::script::palettes`]): each shown palette is a window beside the documents +//! that stays open after the run, with the controls the engine laid out. A click, a change or the +//! window's close box waits in the session's line and runs as a script run of its own once no run +//! is going ([`crate::script_runs::poll`]); the palette stays usable while a run goes on, and its +//! events wait for it. A palette does not take the keyboard focus when it opens or changes. An edit +//! field's text is given when it loses the focus, at Enter in a one-line field, or before a click +//! or a close; a text the script would refuse stays in its field with the error in the status bar. + +use serde_json::json; +use vectorcraft_engine::script::{ScriptPalette, UiEvent}; + +use crate::VectorcraftApp; +use crate::dialogs::script_window; +use crate::state::Dialog; + +/// The largest part of a palette's content shown at once; a larger palette scrolls. +const MAX_SHOWN: egui::Vec2 = egui::vec2(960.0, 640.0); + +/// Where the text typed in a palette's fields is kept between frames. +fn drafts_id(id: u64) -> egui::Id { + egui::Id::unique(("script-palette-drafts", id)) +} + +/// Draws each shown palette, and puts the events the person gives in line. +pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { + let shown: Vec = app.session.script_palettes().iter().filter(|p| p.visible).cloned().collect(); + for p in shown { + let mut drafts = ctx.data(|m| m.get_temp::(drafts_id(p.id))).unwrap_or_else(|| Dialog::new(script_window::KIND, json!({}))); + let mut events = Vec::new(); + let mut open = true; + let title = p.dialog.title(); + let title = if title.is_empty() { tl!("Script Alert").to_string() } else { vectorcraft_engine::script::dialogs::shown_text(title, false) }; + let (width, height) = p.dialog.size(); + let size = egui::vec2(width.max(1.0), height.max(1.0)); + egui::Window::new(title).id(egui::Id::unique(("script-palette", p.id))).open(&mut open).collapsible(false).resizable(false).show(ctx, |ui| { + 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()); + for (i, n) in p.dialog.nodes.iter().enumerate().skip(1) { + if n.visible + && let Some(e) = script_window::control(ui, &mut drafts, area.min, (i, n, script_window::prompt_of(&p.dialog, i)), false) + { + events.push(e); + } + } + }); + }); + if !open { + events.push(UiEvent::Close); + } + drafted(app, &p, &mut drafts, &mut events); + ctx.data_mut(|m| m.insert_temp(drafts_id(p.id), drafts)); + give(app, ctx, p.id, events); + } +} + +/// Puts the text still typed in palette `p`'s fields (`drafts`) before a click or a close in +/// `events`. A text the script would refuse stays in its field with its error in the status bar, +/// and a click or a close waits for the person to fix it. +pub(crate) fn drafted(app: &mut VectorcraftApp, p: &ScriptPalette, drafts: &mut Dialog, events: &mut Vec) { + if let Some(e) = script_window::keep_refused_texts(&p.dialog, drafts, events) { + app.status(e); + } + if events.iter().any(|e| matches!(e, UiEvent::Click(_) | UiEvent::Close)) + && let Err(e) = script_window::commit_drafts(&p.dialog, drafts, events) + { + events.retain(|e| !matches!(e, UiEvent::Click(_) | UiEvent::Close)); + app.status(e); + } +} + +/// Puts the events the person gave the palette `id` in line, or shows why one was refused. +pub(crate) fn give(app: &mut VectorcraftApp, ctx: &egui::Context, id: u64, events: Vec) { + for e in events { + match app.session.script_palette_event(id, e) { + // The next frame starts its run. + Ok(_) => ctx.request_repaint(), + Err(e) => app.status(e), + } + } +} + +/// Starts the run of the oldest waiting palette event when no run is going. → whether one started. +pub(crate) fn start_next(app: &mut VectorcraftApp) -> bool { + match app.session.script_palette_start() { + None => false, + Some(Ok(_)) => true, + Some(Err(e)) => { + crate::script_runs::failed(app, e.to_string()); + false + } + } +} diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 27e74d820e..c40c4a2f6e 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -2,7 +2,8 @@ //! 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`, a ScriptUI dialog's `show()` or a `File` or `Folder` file dialog, -//! waits for the person's answer. +//! waits for the person's answer. With no run going, the oldest event a ScriptUI palette waits +//! with starts its run ([`crate::script_palettes`]). use serde_json::json; @@ -13,7 +14,8 @@ use crate::state::Dialog; /// Advances the running script by one slice, or asks what its growth needs asked. pub fn poll(app: &mut VectorcraftApp) { script_run::drain(app); - if !app.session.script_running() { + // With no run going, a waiting palette event starts its run. + if !app.session.script_running() && !crate::script_palettes::start_next(app) { return; } script_run::settle_close(app); diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index ac934f6d18..2c79788097 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -42,6 +42,7 @@ mod screenmode; mod screenshots; mod script_check; mod script_dialogs; +mod script_palettes; mod script_run; mod script_window; mod scripts_menu; diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs new file mode 100644 index 0000000000..113c501162 --- /dev/null +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -0,0 +1,109 @@ +//! A script's ScriptUI palette in the app: it stays open after the run, and a click on it waits in +//! line and starts its handler's run on the next frame. + +use serde_json::json; +use vectorcraft_engine::Session; +use vectorcraft_engine::script::{UiEvent, UiValue}; + +use crate::dialogs::script_window; +use crate::state::Dialog; +use crate::{VectorcraftApp, menus, script_palettes, 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 run_to_end(app: &mut VectorcraftApp) { + for _ in 0..10_000 { + if !app.session.script_running() { + return; + } + script_runs::poll(app); + } + panic!("the script did not end"); +} + +/// One headless frame in which `f` runs. → whether the frame asked for the next one at once. +fn frame(ctx: &egui::Context, f: impl FnMut(&mut egui::Ui)) -> bool { + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, f); + out.textures_delta.clear(); + out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.repaint_delay.is_zero()) +} + +#[test] +fn a_click_on_a_palette_asks_for_the_frame_that_starts_its_run() { + let mut app = app(); + let source = "#targetengine tools\nvar p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { vc.log('clicked'); }; p.show();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let id = app.session.script_palettes()[0].id; + let ctx = egui::Context::default(); + for _ in 0..3 { + frame(&ctx, |_| {}); + } + assert!(!frame(&ctx, |_| {}), "an idle frame asks for no other"); + assert!(frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])), "the click asks for the next frame"); + assert_eq!(app.session.script_palette_events_waiting(), 1); + script_runs::poll(&mut app); + run_to_end(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked"])); + assert_eq!(app.session.script_palette_events_waiting(), 0); +} + +#[test] +fn a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() { + let mut app = app(); + let source = "#targetengine tools\nvar p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { vc.log('clicked'); }; p.show();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let id = app.session.script_palettes()[0].id; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": "vc.log(confirm('Go?'));", "name": "d.js"})).unwrap().unwrap(); + for _ in 0..10_000 { + if app.session.script_dialog().is_some() { + break; + } + script_runs::poll(&mut app); + } + assert!(app.session.script_dialog().is_some(), "the run waits at its confirm"); + let ctx = egui::Context::default(); + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])); + assert_eq!(app.session.script_palette_events_waiting(), 1); + let mut asks = true; + for _ in 0..5 { + app.begin_host_iteration(); + asks = frame(&ctx, |ui| app.tick(ui.ctx())); + if !asks { + break; + } + } + assert!(!asks, "the waiting click asks for no frames while the run waits for its answer"); + assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits"); +} + +#[test] +fn a_typed_text_the_script_refuses_keeps_the_palette_click_out_of_line() { + let mut app = app(); + let source = "#targetengine texts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); go.onClick = function () { vc.log(t.text); }; p.show();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let p = app.session.script_palettes()[0].clone(); + let long = "x".repeat(16 * 1024 + 1); + let mut drafts = Dialog::new(script_window::KIND, json!({})); + drafts.fields.insert("text1".into(), json!(long)); + let mut events = vec![UiEvent::Change(1, UiValue::Text(long.clone())), UiEvent::Click(2)]; + script_palettes::drafted(&mut app, &p, &mut drafts, &mut events); + assert!(events.is_empty(), "neither the long text nor the click is given: {events:?}"); + assert_eq!(drafts.fields.get("text1"), Some(&json!(long)), "the refused text stays in its field"); + drafts.fields.insert("text1".into(), json!("fine")); + let mut events = vec![UiEvent::Click(2)]; + script_palettes::drafted(&mut app, &p, &mut drafts, &mut events); + assert_eq!(events, vec![UiEvent::Change(1, UiValue::Text("fine".into())), UiEvent::Click(2)]); + assert!(!drafts.fields.contains_key("text1"), "the text is given once"); +} diff --git a/docs/mcp.md b/docs/mcp.md index 951edebb05..36f0993663 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2547,9 +2547,9 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, - `needs` lists what the script needs from the app that runs it: `language` (the script language's own objects and directives, such as `$`, `alert`, `UnitValue`, `#target` and `#targetengine`), `dom` (the reference app's - document model), `files`, `menuCommands`, `dialogs`, and `hostOnly` (features only the reference app has: - palettes, BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, reflection, actions - and `selectTool`). + document model), `files`, `menuCommands`, `dialogs` (dialogs and palettes), and `hostOnly` (features only the + reference app has: BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, + reflection, actions and `selectTool`). - `directives` lists the `#include`, `#includepath`, `#script`, `#strict`, `#target` and `#targetengine` lines, and `targets` splits each `#target` line's application specifier into `app`, `instance`, `version` and `locale`. A directive is read where it starts a line, written `#name` or `//@name`. @@ -2902,8 +2902,9 @@ 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. +- `new Window("dialog"[, title, bounds, properties])` makes a dialog, and `new Window("palette", ...)` a palette, + which is described after the dialogs below. The type `window` and a resource string throw 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`, @@ -2967,6 +2968,45 @@ an error in a handler ends `show()`, with steps it did not use. 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"}]}]}' ``` +A palette is a ScriptUI window that stays open beside the documents after the script that showed it has ended, and +that the person can use while they work (the window-object help page above). A script builds it like a dialog, with +the same controls, handlers and limits: + +- A palette needs a named engine, which keeps its controls and handlers after the run. In a script without + `#targetengine`, or with `#targetengine main`, `new Window("palette")` throws an `Error` that says to add a + `#targetengine` line (see [Script engines](#script-engines)). +- `show()` runs `onShow` and returns `undefined` at once. `hide()` hides the palette, and `show()` shows it again. + `close()` runs `onClose` and closes the palette unless `onClose` returns `false`; the close box does the same. + A palette also closes when `script.engine.drop` drops its engine, when its engine ends with an internal error, + and when the session ends. The palette shows its controls as `show()`, `add()`, each event's handlers and each + run of its engine leave them; a run that a limit or `script.stop` ended can leave it showing them as they were. + A handler's run reads and writes the files the person allowed the script that first showed the palette. +- Each click, change or close the person gives a palette runs its handler as a run of its own in the palette's + engine, with its own report and, when it changes a document, its own Run Script undo step. While another run + goes on, the event waits and runs after it; events run one at a time, oldest first. While an event waits, a + newer click on the same control, change of the same control or close of the same palette takes its place, + with the newer value. A list's change ends its run with an error when a script added or removed the list's + items after the person chose, even if the list again holds the same texts. A text typed in a palette's field + that is longer than 16 KiB stays in the field with the error in the status bar, and a click or close waits + until it is fixed. An error in a handler ends that run like any failed run, puts the documents back, and + leaves the palette open. In the app, `alert`, `confirm`, `prompt` and a dialog's `show()` throw inside a + handler; with nobody to ask, a handler's run has no `answers` and ends at the first of them. +- A session keeps at most 16 palettes, shown or hidden, past which `show()` throws a `RangeError`, and at most 64 + waiting events, past which an event is refused. Hiding or closing a palette drops its waiting events. These + limits are VectorCraft's own. + +`script.palettes {}` lists the palettes in the order they were first shown: `{palettes: [{id, engine, title, +visible, controls: [{index, kind, name, text, enabled, visible, value?, items?, selection?}]}], waiting, limit: 16, +waitingLimit: 64}`. `script.palette.event {palette, event, control?, value?}` gives a shown palette a `click`, a +`change` or a `close`, with `control` and `value` as in a `window` answer's step (`control` can also be a control's +index). In the app it returns `{waiting: true, merged, waitingEvents}`, and the handler's report is later in +`ui.inspect`'s `scriptReport`. With nobody to ask, it runs the waiting events and returns the report of this one, +or its error. A hidden palette, a disabled or hidden control, and a control that cannot take the event are errors. + +```sh +vectorcraft-cli run --cmd script.run --params '{"source": "#targetengine tools\nvar p = new Window(\"palette\", \"Tools\"); var go = p.add(\"button\", undefined, \"Add\"); go.onClick = function () { vc.run(\"shape.rectangle\", {x: 0, y: 0, width: 20, height: 20}); }; p.show();"}' +``` + 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 939047032e..c8f4bb0095 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1066,7 +1066,8 @@ 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`. + - 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. 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`. + - Scripts: ScriptUI's `new Window("palette")` in a script with `#targetengine` shows a palette that stays open beside the documents after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going; a newer event for the same control takes a waiting one's place. A palette closes with `close()`, its close box, or the end of its engine or the session; at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.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`). From 9beb3bb5f9c579eee1ba86e45e5dfa5ff9207090 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:57:39 -0800 Subject: [PATCH 02/34] Scripts: a ScriptUI dialog shown in place of another gives its first field the focus A dialog a script shows right after closing the open one now counts as newly opened: the control used in the first dialog gives up the keyboard focus, and the first editable field of the new dialog takes it. ScriptUI edit fields now take the first-field focus like the app's other dialogs. --- crates/ui-egui/src/dialogs.rs | 23 +++++++--- crates/ui-egui/src/dialogs/script_window.rs | 12 +++++- crates/ui-egui/src/tests/script_window.rs | 47 +++++++++++++++++++++ 3 files changed, 76 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6b59f7bd88..20f57ad04f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -929,7 +929,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { revolve_gizmo::clear(ctx); app.ui.dialog_file = None; ctx.data_mut(|m| { - m.remove::(shown_id); + m.remove::<(String, Option)>(shown_id); m.remove::(focus_id); }); return; @@ -937,13 +937,26 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if !revolve_gizmo::active(&d) { revolve_gizmo::clear(ctx); } - let focus_first = ctx.data_mut(|m| { - if m.get_temp::(shown_id).as_deref() != Some(d.kind.as_str()) { - m.insert_temp(shown_id, d.kind.clone()); + // A ScriptUI dialog that a script showed in place of the one open is a new dialog too. + let shown_as = (d.kind.clone(), script_window::shown_of(&d)); + let (focus_first, replaced) = ctx.data_mut(|m| { + let before = m.get_temp::<(String, Option)>(shown_id); + let replaced = before.as_ref().is_some_and(|b| b.0 == shown_as.0 && *b != shown_as); + if before.as_ref() != Some(&shown_as) { + m.insert_temp(shown_id, shown_as); m.insert_temp(focus_id, true); } - m.get_temp::(focus_id).unwrap_or(false) + (m.get_temp::(focus_id).unwrap_or(false), replaced) }); + // It draws in the same window with the same control ids, so the control used in the dialog + // before it gives up the keyboard focus. + if replaced { + ctx.memory_mut(|m| { + if let Some(id) = m.focused() { + m.surrender_focus(id); + } + }); + } // Not in the frame of a click (the one on the menu item that opened it): egui takes the focus // from a field the click missed, so the field takes it a frame later (#1367). let clicked = ctx.input(|i| i.pointer.any_click()); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 9aea178b9a..a1ea69f620 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -54,6 +54,11 @@ 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) } +/// Which `show()` of the run `d` is open for, when it is a ScriptUI dialog. +pub(crate) fn shown_of(d: &Dialog) -> Option { + if d.kind == KIND { d.fields.get(SHOWN_KEY).and_then(Value::as_u64) } else { None } +} + 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) } @@ -357,8 +362,13 @@ pub(crate) fn screen_reader_name(n: &UiNode, prompt: &str) -> String { fn edit(ui: &mut egui::Ui, d: &mut Dialog, rect: egui::Rect, (i, n, prompt): (usize, &UiNode, &str)) -> 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 id = ui.make_persistent_id("edit"); + // The first field that can be typed in takes the keyboard focus as the dialog opens. + if !n.readonly { + widgets::take_dialog_focus(ui, id, &text); + } 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())); + let r = ui.put(rect, field.id(id).interactive(!n.readonly).desired_width(rect.width())); name_for_screen_readers(ui, &r, n, prompt); if r.changed() { d.fields.insert(key.clone(), json!(text)); diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 2e2cd186ca..5a0b7aeeac 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -210,6 +210,53 @@ fn a_second_dialog_replaces_the_first() { assert_eq!(log(&app), json!([[1, "y"]])); } +/// Draws one frame of the dialog layer for screen readers. → The role of the control with the +/// keyboard focus. +fn focused_role(app: &mut VectorcraftApp) -> Option { + let ctx = CTX.with(Clone::clone); + ctx.enable_accesskit(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + let update = out.platform_output.accesskit_update?; + update.nodes.iter().find(|(id, _)| *id == update.focus).map(|(_, n)| n.role()) +} + +#[test] +fn a_dialog_shown_in_place_of_another_gives_its_first_field_the_focus() { + use egui::accesskit::Role; + 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('statictext', undefined, 'Name'); b.add('button', undefined, 'Back'); \ + b.add('edittext', undefined, 'y'); b.add('button', undefined, 'OK'); vc.log(b.show());", + ); + assert!(until_window(&mut app)); + frame(&mut app, Vec::new()); + frame(&mut app, Vec::new()); + let role = focused_role(&mut app); + assert!(matches!(role, Some(Role::TextInput | Role::MultilineTextInput)), "the first dialog's field has the focus, not {role:?}"); + let mut on_button = false; + for _ in 0..4 { + frame(&mut app, vec![key(egui::Key::Tab)]); + on_button = focused_role(&mut app) == Some(Role::Button); + if on_button { + break; + } + } + assert!(on_button, "Tab puts the focus on the first dialog's button"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(until_window(&mut app)); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("title"), "B"); + frame(&mut app, Vec::new()); + frame(&mut app, Vec::new()); + let role = focused_role(&mut app); + assert!(matches!(role, Some(Role::TextInput | Role::MultilineTextInput)), "the second dialog's field has the focus, not {role:?}"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + #[test] fn a_dialog_function_after_show_opens_its_own_dialog() { let mut app = app(); From d814cb77f3cf3431b6b8ac50a34d927459777a41 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 13:09:54 -0800 Subject: [PATCH 03/34] Scripts: palette events and typed texts stay with their control when a run adds controls A click or change that waits for a palette's run now keeps where its control sits in the palette, and a text typed in a palette's field keeps where its field sits, so both reach the same control after a run adds controls before it. A waiting event whose control is gone is dropped. ScriptUiDialog::place_of and control_at move to the engine so the palette queue and the dialog's queued events use the same rule. --- crates/engine/src/script/palettes.rs | 45 ++++++++++++++------ crates/engine/src/script/scriptui.rs | 27 ++++++++++++ crates/engine/src/tests/script_palettes.rs | 21 ++++++++++ crates/ui-egui/src/dialogs/script_window.rs | 46 +++++---------------- crates/ui-egui/src/script_palettes.rs | 18 +++++++- crates/ui-egui/src/tests/script_palettes.rs | 23 +++++++++++ docs/mcp.md | 7 ++-- 7 files changed, 133 insertions(+), 54 deletions(-) diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index d6ff578f29..5da1b6e888 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -61,6 +61,10 @@ pub enum Waiting { pub(crate) struct Queued { pub(crate) palette: u64, pub(crate) event: UiEvent, + /// Where the control of a click or a change sits in the palette ([`ScriptUiDialog::place_of`]), + /// by which the event finds its control again when a run adds controls before it; empty for a + /// close. + place: Vec, /// For a list's change, the list's items as the palette showed them when the event was given and /// the list's revision then ([`super::scriptui::UiNode::revision`]), which the run checks the list /// still has. @@ -80,12 +84,21 @@ pub(crate) struct Palettes { pub(crate) starting: Option, } -/// Do `a` and `b` share one place in line: a click on the same control, a change of it, or a close? -fn same_place(a: &UiEvent, b: &UiEvent) -> bool { - match (a, b) { - (UiEvent::Click(x), UiEvent::Click(y)) | (UiEvent::Change(x, _), UiEvent::Change(y, _)) => x == y, - (UiEvent::Close, UiEvent::Close) => true, - _ => false, +/// Does `event`, for the control at `place`, share the waiting `q`'s place in line: a click on the +/// same control, a change of it, or a close? +fn same_place(q: &Queued, event: &UiEvent, place: &[usize]) -> bool { + let same_kind = matches!( + (&q.event, event), + (UiEvent::Click(_), UiEvent::Click(_)) | (UiEvent::Change(..), UiEvent::Change(..)) | (UiEvent::Close, UiEvent::Close) + ); + same_kind && q.place == place +} + +/// The control of a click or a change. +fn control_of(event: &mut UiEvent) -> Option<&mut usize> { + match event { + UiEvent::Click(c) | UiEvent::Change(c, _) => Some(c), + UiEvent::Close => None, } } @@ -151,12 +164,13 @@ impl Palettes { if !p.visible { return Err(format!("the script palette {id} is hidden")); } - let event = scriptui::check_event(&p.dialog, event)?; + let mut event = scriptui::check_event(&p.dialog, event)?; let list = match &event { UiEvent::Change(c, UiValue::Index(_)) => p.dialog.nodes.get(*c).map(|n| (n.items.clone(), n.revision)), _ => None, }; - if let Some(slot) = self.waiting.iter_mut().find(|q| q.palette == id && same_place(&q.event, &event)) { + let place = control_of(&mut event).map_or_else(Vec::new, |c| p.dialog.place_of(*c)); + if let Some(slot) = self.waiting.iter_mut().find(|q| q.palette == id && same_place(q, &event, &place)) { slot.event = event; slot.list = list; return Ok(Waiting::Merged); @@ -164,16 +178,21 @@ impl Palettes { if self.waiting.len() >= MAX_WAITING { return Err(format!("{MAX_WAITING} script palette events already wait; this one was not kept")); } - self.waiting.push_back(Queued { palette: id, event, list, grants: None }); + self.waiting.push_back(Queued { palette: id, event, place, list, grants: None }); Ok(Waiting::Added) } - /// The oldest waiting event whose palette is still shown, and that palette. + /// The oldest waiting event whose palette is still shown, given to the control at its place in + /// the palette as the runs since left it, and that palette. An event whose control the palette + /// no longer has is dropped. fn next(&mut self) -> Option<(ScriptPalette, Queued)> { - while let Some(q) = self.waiting.pop_front() { - if let Some(p) = self.list.iter().find(|p| p.id == q.palette && p.visible) { - return Some((p.clone(), q)); + while let Some(mut q) = self.waiting.pop_front() { + let Some(p) = self.list.iter().find(|p| p.id == q.palette && p.visible) else { continue }; + if let Some(c) = control_of(&mut q.event) { + let Some(at) = p.dialog.control_at(&q.place) else { continue }; + *c = at; } + return Some((p.clone(), q)); } None } diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index 8ca7154e47..fd3bda32a4 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -201,6 +201,33 @@ impl ScriptUiDialog { }; by(true).or_else(|| by(false)) } + + /// Where control `i` sits: its position among its container's controls, after its container's + /// own position, and so on up to the dialog. `add` puts a new control after the others in its + /// container, so adding controls leaves the place of every other one as it was, while its index + /// in [`Self::nodes`] can move. Empty for the dialog and for an index it does not have. + pub fn place_of(&self, mut i: usize) -> Vec { + let mut place = Vec::new(); + while i > 0 { + let Some(n) = self.nodes.get(i) else { return Vec::new() }; + place.push(self.nodes.iter().take(i).skip(1).filter(|m| m.parent == n.parent).count()); + if n.parent >= i { + return Vec::new(); + } + i = n.parent; + } + place.reverse(); + place + } + + /// The index of the control at `place` ([`Self::place_of`]), if the dialog has one there. + pub fn control_at(&self, place: &[usize]) -> Option { + let mut at = 0; + for &k in place { + at = self.nodes.iter().enumerate().skip(1).filter(|(_, n)| n.parent == at).nth(k)?.0; + } + (at > 0).then_some(at) + } } /// A value a control takes in a change. diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 006f022627..9c4b7be294 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -153,6 +153,27 @@ fn a_list_change_that_waited_while_the_list_changed_ends_its_run() { assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["b"])); } +#[test] +fn a_click_that_waited_while_a_run_added_a_control_before_it_reaches_its_button() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine places\nvar p = new Window('palette'); var g = p.add('group'); g.add('button', undefined, 'First'); \ + var last = p.add('button', undefined, 'Last'); last.onClick = function () { vc.log('last'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palettes()[0].dialog.find("Last"), Some(3)); + let added = "#targetengine places\nconfirm('Go?'); g.add('button', undefined, 'Added').onClick = function () { vc.log('added'); };"; + assert_eq!(run(&mut s, added).unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(3)), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert_eq!(s.script_palettes()[0].dialog.find("Last"), Some(4), "the added button comes before Last in the list of controls"); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["last"])); +} + #[test] fn a_palette_click_during_another_run_runs_after_it() { let mut s = one_doc(); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 2662e30d87..2c8f35365e 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -143,7 +143,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc if let Value::Object(mut fields) = next { // The control the event was given to, found again in the dialog as the handlers that ran // since left it. - let at = fields.remove(PLACE_KEY).and_then(|p| serde_json::from_value::>(p).ok()).and_then(|p| control_at(&w, &p)); + let at = fields.remove(PLACE_KEY).and_then(|p| serde_json::from_value::>(p).ok()).and_then(|p| w.control_at(&p)); if let Some(i) = at { fields.insert("control".into(), json!(i)); } @@ -152,36 +152,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc DialogAction::Confirm } -/// The field of a queued event that holds where its control sits in the dialog ([`place_of`]). +/// The field of a queued event that holds where its control sits in the dialog +/// ([`ScriptUiDialog::place_of`]). const PLACE_KEY: &str = "place"; -/// Where control `i` sits in the dialog `w`: its position among its container's controls, after -/// its container's own position, and so on up to the dialog. `add` puts a new control after the -/// others in its container, so a handler that adds controls leaves the place of every other one -/// as it was, while its index in the dialog's list of elements can move. -fn place_of(w: &ScriptUiDialog, mut i: usize) -> Vec { - let mut place = Vec::new(); - while i > 0 { - let Some(n) = w.nodes.get(i) else { return Vec::new() }; - place.push(w.nodes.iter().take(i).skip(1).filter(|m| m.parent == n.parent).count()); - if n.parent >= i { - return Vec::new(); - } - i = n.parent; - } - place.reverse(); - place -} - -/// The index of the control at `place` ([`place_of`]) in the dialog `w`, if it has one. -fn control_at(w: &ScriptUiDialog, place: &[usize]) -> Option { - let mut at = 0; - for &k in place { - at = w.nodes.iter().enumerate().skip(1).filter(|(_, n)| n.parent == at).nth(k)?.0; - } - (at > 0).then_some(at) -} - /// The 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"; @@ -245,14 +219,14 @@ fn draft_key(i: usize) -> String { format!("text{i}") } -/// The field that holds, for each text typed in an edit field, where the field sat ([`place_of`]) -/// in the dialog the text was typed in. +/// The field that holds, for each text typed in an edit field, where the field sat +/// ([`ScriptUiDialog::place_of`]) in the dialog the text was typed in. const DRAFT_PLACES_KEY: &str = "draftPlaces"; /// Records where the field of each typed text sits in the dialog `w`, for [`move_drafts`]. -fn note_draft_places(w: &ScriptUiDialog, d: &mut Dialog) { +pub(crate) fn note_draft_places(w: &ScriptUiDialog, d: &mut Dialog) { let places: serde_json::Map = - (1..w.nodes.len()).map(|i| (i, draft_key(i))).filter(|(_, k)| d.fields.contains_key(k)).map(|(i, k)| (k, json!(place_of(w, i)))).collect(); + (1..w.nodes.len()).map(|i| (i, draft_key(i))).filter(|(_, k)| d.fields.contains_key(k)).map(|(i, k)| (k, json!(w.place_of(i)))).collect(); if places.is_empty() { d.fields.remove(DRAFT_PLACES_KEY); } else { @@ -263,12 +237,12 @@ fn note_draft_places(w: &ScriptUiDialog, d: &mut Dialog) { /// Puts each typed text that [`note_draft_places`] recorded under the index its field has in the /// dialog `w`, which moves when a handler adds controls before the field. A text whose field the /// dialog no longer has is dropped. -fn move_drafts(w: &ScriptUiDialog, d: &mut Dialog) { +pub(crate) fn move_drafts(w: &ScriptUiDialog, d: &mut Dialog) { let Some(Value::Object(places)) = d.fields.remove(DRAFT_PLACES_KEY) else { return }; let mut moved = Vec::new(); for (key, place) in places { let Some(text) = d.fields.remove(&key) else { continue }; - let at = serde_json::from_value::>(place).ok().and_then(|p| control_at(w, &p)); + let at = serde_json::from_value::>(place).ok().and_then(|p| w.control_at(&p)); if let Some(i) = at.filter(|i| w.nodes.get(*i).is_some_and(|n| n.kind == UiKind::EditText)) { moved.push((draft_key(i), text)); } @@ -466,7 +440,7 @@ fn event_fields(w: &ScriptUiDialog, event: &UiEvent) -> Value { }; let mut fields = json!({"event": name, "control": control, "value": value}); if let Some(i) = control { - fields[PLACE_KEY] = json!(place_of(w, i)); + fields[PLACE_KEY] = json!(w.place_of(i)); } fields } diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index 125adf0365..ec2e8773dd 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -26,7 +26,7 @@ fn drafts_id(id: u64) -> egui::Id { pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let shown: Vec = app.session.script_palettes().iter().filter(|p| p.visible).cloned().collect(); for p in shown { - let mut drafts = ctx.data(|m| m.get_temp::(drafts_id(p.id))).unwrap_or_else(|| Dialog::new(script_window::KIND, json!({}))); + let mut drafts = drafts(ctx, &p); let mut events = Vec::new(); let mut open = true; let title = p.dialog.title(); @@ -49,11 +49,25 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { events.push(UiEvent::Close); } drafted(app, &p, &mut drafts, &mut events); - ctx.data_mut(|m| m.insert_temp(drafts_id(p.id), drafts)); + keep_drafts(ctx, &p, drafts); give(app, ctx, p.id, events); } } +/// The text typed in palette `p`'s fields, each under the index its field has in `p` now, which +/// moves when a run adds controls before the field. +pub(crate) fn drafts(ctx: &egui::Context, p: &ScriptPalette) -> Dialog { + let mut drafts = ctx.data(|m| m.get_temp::(drafts_id(p.id))).unwrap_or_else(|| Dialog::new(script_window::KIND, json!({}))); + script_window::move_drafts(&p.dialog, &mut drafts); + drafts +} + +/// Keeps the text typed in palette `p`'s fields for the next frame, with where each field sits. +pub(crate) fn keep_drafts(ctx: &egui::Context, p: &ScriptPalette, mut drafts: Dialog) { + script_window::note_draft_places(&p.dialog, &mut drafts); + ctx.data_mut(|m| m.insert_temp(drafts_id(p.id), drafts)); +} + /// Puts the text still typed in palette `p`'s fields (`drafts`) before a click or a close in /// `events`. A text the script would refuse stays in its field with its error in the status bar, /// and a click or a close waits for the person to fix it. diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 113c501162..56cd162316 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -86,6 +86,29 @@ fn a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() { assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits"); } +#[test] +fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() { + let mut app = app(); + let source = "#targetengine places\nvar p = new Window('palette'); var g = p.add('group'); g.add('button', undefined, 'First'); \ + var t = p.add('edittext', undefined, ''); p.show();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let before = app.session.script_palettes()[0].clone(); + assert_eq!(before.dialog.nodes[3].kind, vectorcraft_engine::script::UiKind::EditText); + let ctx = egui::Context::default(); + let mut drafts = script_palettes::drafts(&ctx, &before); + drafts.fields.insert("text3".into(), json!("typed")); + script_palettes::keep_drafts(&ctx, &before, drafts); + let added = "#targetengine places\ng.add('button', undefined, 'Added');"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": added, "name": "a.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let after = app.session.script_palettes()[0].clone(); + assert_eq!(after.dialog.nodes[4].kind, vectorcraft_engine::script::UiKind::EditText, "the added button comes before the field"); + let drafts = script_palettes::drafts(&ctx, &after); + assert_eq!(drafts.fields.get("text4"), Some(&json!("typed")), "{:?}", drafts.fields); + assert!(!drafts.fields.contains_key("text3")); +} + #[test] fn a_typed_text_the_script_refuses_keeps_the_palette_click_out_of_line() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 1fd0e6d865..eee919e83c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2988,9 +2988,10 @@ the same controls, handlers and limits: engine, with its own report and, when it changes a document, its own Run Script undo step. While another run goes on, the event waits and runs after it; events run one at a time, oldest first. While an event waits, a newer click on the same control, change of the same control or close of the same palette takes its place, - with the newer value. A list's change ends its run with an error when a script added or removed the list's - items after the person chose, even if the list again holds the same texts. A text typed in a palette's field - that is longer than 16 KiB stays in the field with the error in the status bar, and a click or close waits + with the newer value. A waiting click or change, and a text typed in a field, stay with their control when a + run adds controls before it; a waiting event whose control is gone is dropped. A list's change ends its run + with an error when a script added or removed the list's items after the person chose, even if the list again + holds the same texts. A text typed in a palette's field that is longer than 16 KiB stays in the field with the error in the status bar, and a click or close waits until it is fixed. An error in a handler ends that run like any failed run, puts the documents back, and leaves the palette open. In the app, `alert`, `confirm`, `prompt` and a dialog's `show()` throw inside a handler; with nobody to ask, a handler's run has no `answers` and ends at the first of them. From f19e114c40227c04e6b8e8a959d852f38ef45d08 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 15:32:54 -0800 Subject: [PATCH 04/34] Scripts: a waiting palette event a handler made its control refuse is dropped A click or change that waits for a palette's run is checked against the palette's controls again before its run starts. When an earlier handler disabled or hid the control, the event is dropped. A list's change whose list a run changed since still ends its run with the error that says so, unless the list can no longer take a change. --- crates/engine/src/script/palettes.rs | 20 ++++++++- crates/engine/src/tests/script_palettes.rs | 48 ++++++++++++++++++++++ docs/mcp.md | 3 +- 3 files changed, 69 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 5da1b6e888..6fdd49b45b 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -184,7 +184,8 @@ impl Palettes { /// The oldest waiting event whose palette is still shown, given to the control at its place in /// the palette as the runs since left it, and that palette. An event whose control the palette - /// no longer has is dropped. + /// no longer has, or that the control can no longer take ([`scriptui::check_event`]), for + /// example because a handler disabled or hid it, is dropped. fn next(&mut self) -> Option<(ScriptPalette, Queued)> { while let Some(mut q) = self.waiting.pop_front() { let Some(p) = self.list.iter().find(|p| p.id == q.palette && p.visible) else { continue }; @@ -192,6 +193,23 @@ impl Palettes { let Some(at) = p.dialog.control_at(&q.place) else { continue }; *c = at; } + // A list's change whose list a run changed since goes to its run, which ends with the + // error that says so, when the list can still take a change: the choice is checked + // without its item, which the list may no longer have. + let list_changed = match (&q.event, &q.list) { + (UiEvent::Change(c, UiValue::Index(_)), Some((_, revision))) => { + p.dialog.nodes.get(*c).is_some_and(|n| n.revision != *revision).then_some(*c) + } + _ => None, + }; + if let Some(c) = list_changed { + if scriptui::check_event(&p.dialog, UiEvent::Change(c, UiValue::Index(None))).is_err() { + continue; + } + } else { + let Ok(event) = scriptui::check_event(&p.dialog, q.event) else { continue }; + q.event = event; + } return Some((p.clone(), q)); } None diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 9c4b7be294..7078442ac2 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -153,6 +153,32 @@ fn a_list_change_that_waited_while_the_list_changed_ends_its_run() { assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["b"])); } +#[test] +fn a_list_change_for_an_item_a_run_removed_since_ends_its_run() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine shrink\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ + l.onChange = function () { vc.log(String(l.selection)); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "#targetengine shrink\nconfirm('Go?'); l.removeAll(); l.add('item', 'a');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Change(1, crate::script::UiValue::Index(Some(1)))), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the change starts its run").is_ok()); + let e = pump(&mut s).unwrap().unwrap_err().to_string(); + assert!(e.contains("a palette's list changed before the person's choice was taken"), "{e}"); + assert_eq!(run(&mut s, "#targetengine shrink\nconfirm('Go?'); l.add('item', 'c'); l.enabled = false;").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Change(1, crate::script::UiValue::Index(Some(0)))), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().is_none(), "a change of a list a run changed and disabled since is dropped"); + assert_eq!(s.script_palette_events_waiting(), 0); +} + #[test] fn a_click_that_waited_while_a_run_added_a_control_before_it_reaches_its_button() { let mut s = one_doc(); @@ -174,6 +200,28 @@ fn a_click_that_waited_while_a_run_added_a_control_before_it_reaches_its_button( assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["last"])); } +#[test] +fn a_waiting_click_on_a_button_a_handler_disabled_is_dropped() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine switches\nvar p = new Window('palette'); var off = p.add('button', undefined, 'Off'); \ + var go = p.add('button', undefined, 'Go'); off.onClick = function () { go.enabled = false; vc.log('off'); }; \ + go.onClick = function () { vc.log('go'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the first click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["off"])); + assert!(s.script_palette_start().is_none(), "the click on the button the handler disabled does not run"); + assert_eq!(s.script_palette_events_waiting(), 0); +} + #[test] fn a_palette_click_during_another_run_runs_after_it() { let mut s = one_doc(); diff --git a/docs/mcp.md b/docs/mcp.md index eee919e83c..2bc012fe73 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2989,7 +2989,8 @@ the same controls, handlers and limits: goes on, the event waits and runs after it; events run one at a time, oldest first. While an event waits, a newer click on the same control, change of the same control or close of the same palette takes its place, with the newer value. A waiting click or change, and a text typed in a field, stay with their control when a - run adds controls before it; a waiting event whose control is gone is dropped. A list's change ends its run + run adds controls before it. A waiting event whose control is gone, or that its control can no longer take + because a handler disabled or hid it, is dropped. A list's change ends its run with an error when a script added or removed the list's items after the person chose, even if the list again holds the same texts. A text typed in a palette's field that is longer than 16 KiB stays in the field with the error in the status bar, and a click or close waits until it is fixed. An error in a handler ends that run like any failed run, puts the documents back, and From 9cbbb23e01e240dbec9b7801f671a529f3b95150 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 15:58:52 -0800 Subject: [PATCH 05/34] Scripts: a palette event waiting for an open undo group asks for no frames While an undo group is open, a palette event's run cannot start. The app asked for a new frame every frame while the event waited, so it never went idle. It now asks for the next frame at once only when the run can start, and otherwise looks again four times a second. --- crates/engine/src/script/palettes.rs | 10 +++++++ crates/ui-egui/src/app.rs | 7 +++-- crates/ui-egui/src/tests/script_palettes.rs | 31 +++++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 6fdd49b45b..1336a6a7f3 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -329,6 +329,16 @@ impl Session { self.script_palettes.waiting.len() } + /// Whether [`Session::script_palette_start`] can start a waiting event's run now: an event + /// waits, no run is going, and no undo group is open, which a run cannot start in. A drag in + /// progress is not counted, since starting the run settles it. + pub fn script_palette_can_start(&self) -> bool { + !self.script_palettes.waiting.is_empty() + && !self.script_running() + && self.explicit_undo_group.is_none() + && self.docs.iter().all(|d| d.undo_group.is_none()) + } + /// Puts `event` for the shown palette `id` in line, to run in its engine once no run is going /// ([`Session::script_palette_start`]). → an error when there is no such shown palette, it /// cannot take the event ([`scriptui::check_event`]), or [`MAX_WAITING`] events already wait. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bd2bba2159..b52abc1a7a 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -369,9 +369,12 @@ impl VectorcraftApp { crate::scripts_menu::poll(self, ctx); crate::dialogs::proof_setup::poll(self, ctx); // A palette event whose run starts on the next frame. While a run goes on, the block below - // asks for its frames, and a run that waits for the person goes on at their next input. - if self.session.script_palette_events_waiting() > 0 && !self.session.script_running() { + // asks for its frames, and a run that waits for the person goes on at their next input. An + // event that waits for an open undo group to end looks again four times a second. + if self.session.script_palette_can_start() { ctx.request_repaint(); + } else if self.session.script_palette_events_waiting() > 0 && !self.session.script_running() { + ctx.request_repaint_after(std::time::Duration::from_millis(250)); } if self.session.script_running() && !self.session.script_waiting() diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 56cd162316..877548d602 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -86,6 +86,37 @@ fn a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() { assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits"); } +#[test] +fn a_click_waiting_for_an_open_undo_group_asks_for_no_frames_and_runs_after_it() { + let mut app = app(); + let source = "#targetengine tools\nvar p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { vc.log('clicked'); }; p.show();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let id = app.session.script_palettes()[0].id; + app.run("edit.undoGroup.begin", json!({})).unwrap(); + let ctx = egui::Context::default(); + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])); + assert_eq!(app.session.script_palette_events_waiting(), 1); + let mut asks = true; + for _ in 0..5 { + app.begin_host_iteration(); + asks = frame(&ctx, |ui| app.tick(ui.ctx())); + if !asks { + break; + } + } + assert!(!asks, "the waiting click asks for no frames while the undo group is open"); + assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits"); + app.run("edit.undoGroup.end", json!({})).unwrap(); + app.begin_host_iteration(); + frame(&ctx, |ui| app.tick(ui.ctx())); + assert_eq!(app.session.script_palette_events_waiting(), 0, "with the group ended the next frame starts the click's run"); + run_to_end(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked"])); + assert_eq!(app.session.script_palette_events_waiting(), 0); +} + #[test] fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() { let mut app = app(); From ab15fbb0d1bd1df64e3b819f4025e711f4b52983 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:32:54 -0800 Subject: [PATCH 06/34] Scripts: palette events keep their errors, and palettes keep visible in step - script.palette.event takes a whole float such as 1.0 as a list's item index, as a window answer does. - With nobody to ask, an event given while an undo group is open is refused with the undo-group error and is not kept. An event whose run cannot begin, for example because a recovery copy cannot be saved, ends the call with its error, and the events after it keep waiting. - A handler's error keeps its file, line and column when a palette getter also throws in the refresh after the run. - A palette's controls reach the host once, after the handler's run ends, so a getter is read once for a run that completes. - The refresh roots its copy of the palette list while getters run. - hide() sets a palette's visible to false, and show() sets it to true once the host shows it. - A close() inside a modal dialog's onClose does nothing, as for a palette; a later close runs onClose again. - A palette list change reads the list's revision after its item texts, whose getters may replace the items. - Bounds given as x, y, width and height keep their right and bottom edges finite. - A palette event that waits for an open undo group asks for no frames; the frame that ends the group asks for the next one. - A list choice queued in a ScriptUI dialog carries the list's items and revision, and is not given when a handler changed the list since. The status message has a row in every complete catalog. - docs/mcp.md: with nobody to ask, the undo-group refusal and the event whose run cannot begin; a handler reads the files allowed with Always. --- crates/engine/src/cmd/scripts.rs | 7 +- crates/engine/src/script/mod.rs | 7 +- crates/engine/src/script/palettes.rs | 24 ++++--- crates/engine/src/tests/script_palettes.rs | 75 +++++++++++++++++++++ crates/js/src/realm.rs | 12 ++++ crates/js/src/scriptui.rs | 49 +++++++++----- crates/js/src/scriptui_tests.rs | 72 +++++++++++++++++++- crates/ui-egui/src/app.rs | 9 ++- crates/ui-egui/src/dialogs/script_window.rs | 29 ++++++++ crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/tests/script_palettes.rs | 16 +++-- crates/ui-egui/src/tests/script_window.rs | 26 +++++++ docs/mcp.md | 7 +- 37 files changed, 316 insertions(+), 42 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 831b56c586..349b46b28f 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Script Palette Event", [], None, - "{palette: an id script.palettes lists, event: click|change|close, control?: a control's index, or its name or text (click and change), value?: an edit field's text, a slider's number, or a list's item index or null (change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; while it waits, another click on the same control, change of it or close of the same palette takes its place with the newer value, and a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", + "{palette: an id script.palettes lists, event: click|change|close, control?: a control's index, or its name or text (click and change), value?: an edit field's text, a slider's number, or a list's item index or null (change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; while it waits, another click on the same control, change of it or close of the same palette takes its place with the newer value, and a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", always, palette_event ), @@ -281,6 +281,11 @@ fn palette_event(s: &mut Session, p: &Value) -> Result { let Some(event) = p.get("event").and_then(Value::as_str) else { return Err(bad(C, "`event` must be click, change or close")) }; let Some(palette) = s.script_palettes().iter().find(|q| q.id == id) else { return Err(bad(C, format!("there is no script palette {id}"))) }; let event = script::palettes::parse_event(&palette.dialog, event, p.get("control"), p.get("value")).map_err(|e| bad(C, e))?; + // With nobody to ask, the event runs now or not at all: it is not kept for after an open undo + // group, which a run cannot start in. + if !s.script_frames && s.undo_group_open() { + return Err(EngineError::Other(script::OPEN_EDIT.to_string())); + } let waiting = s.script_palette_event(id, event).map_err(|e| bad(C, e))?; if s.script_frames { return Ok(json!({"waiting": true, "merged": waiting == script::Waiting::Merged, "waitingEvents": s.script_palette_events_waiting()})); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index de8f299cec..ef204e4582 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2345,7 +2345,7 @@ impl Session { } } -const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script"; +pub(crate) const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script"; const INVALID_RESULT: &str = "the script left a document that cannot be kept"; const UNWRITTEN_FILES: &str = "Error: the script left open files that could not be written"; const JOB_GONE: &str = "the script's run is no longer available"; @@ -2515,9 +2515,10 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result realm.refresh_script_ui().map(|()| Progress::Done(v)), // A failed run keeps its globals, so its palettes show what it left too; a refresh - // that fails as well (the fuel is spent, a stop) leaves them as they were. + // that fails as well (the fuel is spent, a stop) leaves them as they were, and the + // run's error keeps its place. Err(e) if named && e.kind != RunErrorKind::Internal => { - let _ = realm.refresh_script_ui(); + realm.refresh_script_ui_after_error(); Err(e) } r => r, diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 1336a6a7f3..e7de94a1bf 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -43,7 +43,8 @@ pub struct ScriptPalette { pub dialog: ScriptUiDialog, pub visible: bool, /// The SHA-256 the file grants of the script that first showed it are kept for, which its - /// handlers' runs keep using. + /// handlers' runs keep using: the grants allowed with Always. A grant allowed once is the + /// showing run's alone, as for any later run of the script. pub(crate) grants: String, } @@ -253,8 +254,8 @@ pub(crate) fn parse_event( ("click", None) => UiEvent::Click(id), ("click", Some(_)) => return Err("a click takes no `value`".into()), ("change", Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())), - ("change", Some(Value::Number(v))) if list => match v.as_u64() { - Some(k) => UiEvent::Change(id, UiValue::Index(Some(usize::try_from(k).unwrap_or(usize::MAX)))), + ("change", Some(Value::Number(v))) if list => match scriptui::list_index(v) { + Some(k) => UiEvent::Change(id, UiValue::Index(Some(k))), None => return Err("a list's `value` must be an item index or null".into()), }, ("change", Some(Value::Number(v))) => UiEvent::Change(id, UiValue::Number(v.as_f64().unwrap_or(f64::NAN))), @@ -333,10 +334,12 @@ impl Session { /// waits, no run is going, and no undo group is open, which a run cannot start in. A drag in /// progress is not counted, since starting the run settles it. pub fn script_palette_can_start(&self) -> bool { - !self.script_palettes.waiting.is_empty() - && !self.script_running() - && self.explicit_undo_group.is_none() - && self.docs.iter().all(|d| d.undo_group.is_none()) + !self.script_palettes.waiting.is_empty() && !self.script_running() && !self.undo_group_open() + } + + /// Whether an undo group is open, the session's or a document's, which a run cannot start in. + pub(crate) fn undo_group_open(&self) -> bool { + self.explicit_undo_group.is_some() || self.docs.iter().any(|d| d.undo_group.is_some()) } /// Puts `event` for the shown palette `id` in line, to run in its engine once no run is going @@ -383,11 +386,14 @@ impl Session { } /// `script.palette.event` with no run going and nobody to ask: runs the waiting events in turn, - /// the one just given last. → that one's report. + /// the one just given last. → that one's report. An event whose run could not begin, for + /// example because the recovery copies could not be saved, ends this with its error, and the + /// events after it keep waiting. pub(crate) fn script_palette_run_waiting(&mut self) -> Result { let mut last = Err(EngineError::Other("no script palette event waits".into())); while let Some(started) = self.script_palette_start() { - last = started.and_then(|_| self.script_run_to_end()); + started?; + last = self.script_run_to_end(); } last } diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 7078442ac2..c432700fe6 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -262,6 +262,81 @@ fn double_clicks_while_queued_run_once() { assert_eq!(logs, [json!(["click 1"]), json!(["change ab"])]); } +#[test] +fn a_list_change_takes_a_whole_float_as_its_item_index() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine floats\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ + l.onChange = function () { vc.log(String(l.selection)); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let picked = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 1, "value": 1.0})).unwrap(); + assert_eq!(picked["log"], json!(["b"])); + for value in [json!(0.5), json!(-1)] { + let given = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 1, "value": value})); + assert!(given.is_err(), "{value}"); + } +} + +#[test] +fn with_nobody_to_ask_an_event_while_an_undo_group_is_open_is_refused_and_not_kept() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + s.execute("edit.undoGroup.begin", &json!({})).unwrap(); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("undo group is open"), "{e}"); + assert_eq!(s.script_palette_events_waiting(), 0, "the refused click does not wait"); + s.execute("edit.undoGroup.end", &json!({})).unwrap(); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"]), "only the click given after the group ran"); +} + +#[test] +fn with_nobody_to_ask_an_event_whose_run_cannot_begin_ends_with_its_error_and_the_next_waits() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Change(2, crate::script::UiValue::Text("a".into()))), Ok(Waiting::Added)); + // The document has changes, and the session has nowhere to keep a recovery copy of it. + s.script_copy_first = true; + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("recovery copy"), "{e}"); + assert_eq!(s.script_palette_events_waiting(), 1, "the click after the change whose run could not begin still waits"); + s.script_copy_first = false; + assert_eq!(s.script_palette_run_waiting().unwrap()["log"], json!(["click 1"])); +} + +#[test] +fn a_handler_s_error_keeps_its_file_when_a_palette_getter_throws_after_it() { + let base = std::env::temp_dir().join(format!("vc-script-palette-place-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let base = std::fs::canonicalize(&base).unwrap(); + let first = base.join("first.jsx"); + std::fs::write( + &first, + "#targetengine places\nvar armed = false; var p = new Window('palette'); var b = p.add('button', undefined, 'Go');\n\ + Object.defineProperty(p, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'P'; }});\np.show();", + ) + .unwrap(); + let second = base.join("second.jsx"); + std::fs::write(&second, "#targetengine places\n\n\nb.onClick = function () { armed = true; throw new Error('handler'); };").unwrap(); + let mut s = one_doc(); + for file in [&first, &second] { + s.execute("script.run", &json!({"path": file.to_string_lossy()})).unwrap(); + } + let id = only_palette(&s); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("handler"), "{e}"); + let report = s.script_report().unwrap(); + assert!(report["file"].as_str().is_some_and(|f| f.ends_with("second.jsx")), "{report}"); + assert_eq!(report["line"], 4, "{report}"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn a_palette_from_a_script_without_a_named_engine_is_refused() { let mut s = one_doc(); diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 117ae759b6..3a65a60f0b 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -512,6 +512,18 @@ impl Realm { } } + /// [`Realm::refresh_script_ui`] after a run that failed: what the refresh throws is dropped, + /// and the run's error keeps its place ([`Realm::error_source`], [`Realm::error_mark`]) and + /// its thrown value. + pub fn refresh_script_ui_after_error(&mut self) { + let (tag, mark) = (self.interp.error_tag, self.interp.error_mark); + let thrown = self.interp.last_thrown.clone(); + let _ = self.refresh_script_ui(); + self.interp.error_tag = tag; + self.interp.error_mark = mark; + self.interp.last_thrown = thrown; + } + /// 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 index 52f42ee49c..dac3e9d590 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -666,14 +666,15 @@ fn close(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult { let (o, palette) = window_of(i, &this, "hide")?; if !palette { @@ -682,6 +683,7 @@ fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { if let Value::Number(id) = slot(i, o, PALETTE_ID)? { let f = host_fn(i, "paletteHide")?; i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + i.put(o, key("visible"), Value::Bool(false), true)?; } Ok(Value::Undefined) } @@ -698,10 +700,7 @@ fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { if slot(i, win, IN_CLOSE)?.truthy() { return Ok(()); } - set_slot(i, win, IN_CLOSE, Value::Bool(true))?; - let allowed = may_close(i, win); - set_slot(i, win, IN_CLOSE, Value::Undefined)?; - if !allowed? { + if !may_close(i, win)? { return Ok(()); } if let Value::Number(id) = slot(i, win, PALETTE_ID)? { @@ -724,10 +723,16 @@ fn update_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { /// Gives the host the controls of every palette it shows, after a handler may have changed them. fn update_palettes(i: &mut Interp) -> JsResult<()> { - for win in classes(i)?.palettes { - update_palette(i, win)?; - } - Ok(()) + // A getter may close a later palette, which removes it from the rooted list, so the copy is + // rooted until the loop ends. + let palettes = classes(i)?.palettes; + let roots: Vec = palettes.iter().map(|&win| Value::Object(win)).collect(); + i.rooted(&roots, |i| { + for win in palettes { + update_palette(i, win)?; + } + Ok(()) + }) } /// Gives the host the controls of every palette the realm keeps, as a run left them @@ -755,15 +760,16 @@ fn palette_shown(i: &mut Interp, keep: &[Value], id: Value) -> JsResult { if !classes(i)?.palettes.contains(&win) { set_palettes(i, |p| p.push(win)); } + i.put(win, key("visible"), Value::Bool(true), true)?; handler(i, win, "onShow")?; update_palette(i, win)?; Ok(Value::Undefined) } /// `Window.__vcPaletteEvent()`, which the run of a palette's handler calls: takes the event from the -/// host's `paletteEvent`, gives it to the palette the way a dialog takes the person's event, and -/// gives the host every palette's controls afterward. An event for a palette that has closed does -/// nothing. +/// host's `paletteEvent` and gives it to the palette the way a dialog takes the person's event. The +/// host gets every palette's controls once the run ends ([`crate::Realm::refresh_script_ui`]). An +/// event for a palette that has closed does nothing. fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { let f = host_fn(i, "paletteEvent")?; let answer = i.call(&f, &Value::Undefined, &[])?; @@ -795,7 +801,6 @@ fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult JsResult { Ok(Value::Number(result)) } -/// Runs `onClose`. → false when it returned `false`. +/// Runs `onClose`, during which a `close()` of the same window does nothing. → false when it +/// returned `false`. fn may_close(i: &mut Interp, win: ObjId) -> JsResult { - Ok(!matches!(handler(i, win, "onClose")?, Some(Value::Bool(false)))) + set_slot(i, win, IN_CLOSE, Value::Bool(true))?; + let ran = handler(i, win, "onClose"); + set_slot(i, win, IN_CLOSE, Value::Undefined)?; + Ok(!matches!(ran?, Some(Value::Bool(false)))) } /// Closes the dialog when a handler asked to, or asks the host's `wait` what happens next. @@ -1005,12 +1014,14 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, } // A palette's list may have changed while the event waited: the host gives // the items the person saw and the list's revision then. + // The revision is read after the texts, whose getters may change the list. None => { + let same = same_items(i, c, &slot(i, ev, "items")?)?; let revised = match slot(i, ev, "revision")? { Value::Number(r) => r != number_slot(i, c, REVISION)?, _ => false, }; - if revised || !same_items(i, c, &slot(i, ev, "items")?)? || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { + if revised || !same || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { return Err(error(i, "a palette's list changed before the person's choice was taken")); } } @@ -1116,7 +1127,9 @@ fn bounds(i: &mut Interp, v: &Value) -> JsResult { 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))])); + // Two finite numbers can add up to infinity; the sum is kept finite. + let end = |a: f64, b: f64| (a + b).clamp(-f64::MAX, f64::MAX); + return Ok(Data::Array(vec![Data::Number(n(0)), Data::Number(n(1)), Data::Number(end(n(0), n(2))), Data::Number(end(n(1), n(3)))])); } numbers(i, v, &["left", "top", "right", "bottom"], "bounds") } diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 76a70d331d..f9be03af3b 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -444,7 +444,10 @@ fn a_palette_s_show_returns_at_once_and_its_events_run_its_handlers() { assert_eq!(names(&calls), ["palette", "paletteShow", "paletteUpdate"]); r.run("Window.__vcPaletteEvent(); Window.__vcPaletteEvent();").unwrap(); assert_eq!(r.run("log.join('|') + '|' + label.text").unwrap(), JsValue::String("click|change typed|clicked".into())); - assert_eq!(calls.borrow().iter().filter(|(n, id)| n == "paletteUpdate" && *id == 1.0).count(), 3, "each event gives the host the new controls"); + let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, id)| n == "paletteUpdate" && *id == 1.0).count(); + assert_eq!(updates(&calls), 1, "the handlers give the host nothing"); + r.refresh_script_ui().unwrap(); + assert_eq!(updates(&calls), 2, "the refresh after the run gives the host the new controls"); assert_eq!(r.run("Window.__vcPaletteEvent(); 'nothing'").unwrap(), JsValue::String("nothing".into()), "no event left: nothing runs"); } @@ -489,6 +492,73 @@ fn a_palette_list_change_after_its_items_changed_throws() { assert_eq!(r.run("got.join()").unwrap(), JsValue::String("b".into())); } +/// A palette list change as the host gives it: the item index, the items the person saw (`a` and +/// `b`) and the revision of a list made with those two items. +fn seen_list_change(index: f64) -> Data { + let Data::Object(mut fields) = palette_event(1.0, change(1, Data::Number(index))) else { return Data::Null }; + fields.push(("items".into(), Data::Array(vec![Data::String("a".into()), Data::String("b".into())]))); + fields.push(("revision".into(), Data::Number(2.0))); + Data::Object(fields) +} + +#[test] +fn a_palette_list_change_after_an_item_s_text_changed_throws() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + r.run("var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; l.onChange = function () { got.push(String(l.selection)); }; p.show();") + .unwrap(); + r.run("l.items[1].text = 'z';").unwrap(); + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into()), "the same items, one with another text"); + assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into())); +} + +#[test] +fn a_palette_list_change_throws_when_an_item_s_text_getter_replaces_the_items() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The event reads the first item's text twice: for the palette's description, then to compare + // it with the items the person saw. The second read replaces the items with ones of the same + // texts. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ + Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { l.removeAll(); l.add('item', 'a'); l.add('item', 'b'); } return 'a'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into())); + assert_eq!(r.run("[reads, got.join()].join()").unwrap(), JsValue::String("2,".into())); +} + +#[test] +fn a_palette_s_visible_follows_hide_and_show() { + let (mut r, _) = palette_realm(Vec::new()); + let v = r + .run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); var a = p.visible; p.hide(); var b = p.visible; p.show(); [a, b, p.visible].join()") + .unwrap(); + assert_eq!(v, JsValue::String("true,false,true".into())); +} + +#[test] +fn a_close_inside_a_dialog_s_on_close_does_nothing() { + let (mut r, seen, _) = realm(vec![close(), click(13)]); + let source = format!( + "{FORM} var asked = 0; w.onClose = function () {{ asked++; if (asked == 1) {{ w.close(5); return false; }} return true; }}; [w.show(), asked].join()" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("2,2".into()), "the dialog waited for the click on Cancel"); + assert_eq!(seen.borrow().ends, vec![(2.0, true)]); +} + +#[test] +fn bounds_whose_ends_add_up_past_the_largest_number_stay_finite() { + let (mut r, seen, _) = realm(vec![close()]); + r.run("var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); b.bounds = {x: 1e308, y: 0, width: 1e308, height: 20}; w.show()") + .unwrap(); + let described = nodes(&seen.borrow().descriptions[0]); + let want = Data::Array(vec![Data::Number(1e308), Data::Number(0.0), Data::Number(f64::MAX), Data::Number(20.0)]); + assert_eq!(field(&described[1], "bounds"), &want); +} + #[test] fn hide_keeps_the_palette_and_show_shows_it_again_with_the_same_id() { let (mut r, calls) = palette_realm(Vec::new()); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b52abc1a7a..7cc5524c25 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -370,11 +370,10 @@ impl VectorcraftApp { crate::dialogs::proof_setup::poll(self, ctx); // A palette event whose run starts on the next frame. While a run goes on, the block below // asks for its frames, and a run that waits for the person goes on at their next input. An - // event that waits for an open undo group to end looks again four times a second. + // event that waits for an open undo group asks for no frame; the pass that ends the group + // asks for the next one (`ui_frame`). if self.session.script_palette_can_start() { ctx.request_repaint(); - } else if self.session.script_palette_events_waiting() > 0 && !self.session.script_running() { - ctx.request_repaint_after(std::time::Duration::from_millis(250)); } if self.session.script_running() && !self.session.script_waiting() @@ -672,6 +671,10 @@ impl VectorcraftApp { } scrub::end_frame(self, &ctx); native_menu::sync(self, &ctx); + // A palette event that waited for an undo group this pass ended starts its run next frame. + if self.session.script_palette_can_start() { + ctx.request_repaint(); + } // Observe once, after all of this pass's input, dialogs, floating panels, palette and // commands: the latest completed pass is authoritative for owner, text and cause. crate::ime::end_of_pass(self, &ctx); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 2c8f35365e..343f6c27d3 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -144,6 +144,15 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc // The control the event was given to, found again in the dialog as the handlers that ran // since left it. let at = fields.remove(PLACE_KEY).and_then(|p| serde_json::from_value::>(p).ok()).and_then(|p| w.control_at(&p)); + // A list's choice whose list a handler changed since it was made is not given. + if !same_list(&w, at, fields.remove(LIST_KEY).as_ref()) { + app.status(LIST_CHANGED); + // The events after it are given from the next frame on. + if d.fields.contains_key(QUEUE_KEY) { + ui.ctx().request_repaint(); + } + return DialogAction::None; + } if let Some(i) = at { fields.insert("control".into(), json!(i)); } @@ -152,6 +161,13 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc DialogAction::Confirm } +/// The field of a queued list change that holds the list's items and revision as the person saw +/// them ([`UiNode::revision`]). +const LIST_KEY: &str = "list"; + +/// The status when a queued list choice is not given because its list changed. +const LIST_CHANGED: &str = "The list's items changed before the choice was taken"; + /// The field of a queued event that holds where its control sits in the dialog /// ([`ScriptUiDialog::place_of`]). const PLACE_KEY: &str = "place"; @@ -442,9 +458,22 @@ fn event_fields(w: &ScriptUiDialog, event: &UiEvent) -> Value { if let Some(i) = control { fields[PLACE_KEY] = json!(w.place_of(i)); } + if let UiEvent::Change(i, UiValue::Index(_)) = event + && let Some(n) = w.nodes.get(*i) + { + fields[LIST_KEY] = json!({"items": n.items, "revision": n.revision}); + } fields } +/// Whether the list control `at` of `w` still holds the items a queued list change was given for +/// (its [`LIST_KEY`] field): the same texts and the same revision. True for any other event. +fn same_list(w: &ScriptUiDialog, at: Option, seen: Option<&Value>) -> bool { + let Some(seen) = seen else { return true }; + let n = at.and_then(|i| w.nodes.get(i)); + n.is_some_and(|n| seen["revision"].as_f64() == Some(n.revision) && seen["items"] == json!(n.items)) +} + /// 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") { diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 51a518f798..055cc437f6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6583,6 +6583,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `answers` must be a list of answers `answers` ha de ser una llista de respostes @msg `answers` has more than {MAX_ANSWERS} answers `answers` té més de {MAX_ANSWERS} respostes @msg {MAX_WAITING} script palette events already wait; this one was not kept ja esperen {MAX_WAITING} esdeveniments de paletes d'scripts; aquest no s'ha conservat +@msg The list's items changed before the choice was taken Els elements de la llista han canviat abans que es prengués l'elecció @msg `answers` is larger than 1 MiB `answers` ocupa més d'1 MiB @msg must be an object with `kind` and `value` ha de ser un objecte amb `kind` i `value` @msg must have exactly `kind` and `value` ha de tenir exactament `kind` i `value` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 9457178baf..17f9bd3929 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8987,6 +8987,7 @@ breakText Glyphs Glyfy @msg `answer` for this {kind} dialog must be one of: {_1} `answer` pro tento dialog {kind} musí být jedna z hodnot: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` má více než {MAX_ANSWERS} odpovědí @msg {MAX_WAITING} script palette events already wait; this one was not kept už čeká {MAX_WAITING} událostí palet skriptů; tato nebyla zachována +@msg The list's items changed before the choice was taken Položky seznamu se změnily dříve, než byla volba převzata @msg `answers` is larger than 1 MiB `answers` je větší než 1 MiB @msg `answers` must be a list of answers `answers` musí být seznam odpovědí @msg `artboard` must be the index of an artboard of the document `artboard` musí být index pracovní plochy dokumentu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 1ef0d2169d..4f64a31c76 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -226,6 +226,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg `answers` must be a list of answers `answers` skal være en liste med svar @msg `answers` has more than {MAX_ANSWERS} answers `answers` har flere end {MAX_ANSWERS} svar @msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} hændelser fra scriptpaletter venter allerede; denne blev ikke gemt +@msg The list's items changed before the choice was taken Listens elementer blev ændret, før valget blev modtaget @msg `answers` is larger than 1 MiB `answers` er større end 1 MiB @msg `answers[{i}]` {e} `answers[{i}]` {e} @msg must be an object with `kind` and `value` skal være et objekt med `kind` og `value` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 935a135c4b..d606cb3196 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8427,6 +8427,7 @@ breakText Glyphs Glyphen @msg `answer` for this {kind} dialog must be one of: {_1} `answer` für dieses {kind}-Dialogfeld muss eines der folgenden sein: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` hat mehr als {MAX_ANSWERS} Antworten @msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} Ereignisse von Skriptpaletten warten bereits; dieses wurde nicht behalten +@msg The list's items changed before the choice was taken Die Einträge der Liste haben sich geändert, bevor die Auswahl übernommen wurde @msg `answers` is larger than 1 MiB `answers` ist größer als 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` ist nur für einen Lauf ohne jemanden, der gefragt werden kann: In der App beantwortet die Person jeden Dialog @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` muss eine ganze Zahl von 1 bis {_1} sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index aa30a34709..4ae2b19c0a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2780,6 +2780,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg `answers` must be a list of answers το `answers` πρέπει να είναι λίστα απαντήσεων @msg `answers` has more than {MAX_ANSWERS} answers το `answers` έχει περισσότερες από {MAX_ANSWERS} απαντήσεις @msg {MAX_WAITING} script palette events already wait; this one was not kept ήδη περιμένουν {MAX_WAITING} συμβάντα παλετών σεναρίων· αυτό δεν κρατήθηκε +@msg The list's items changed before the choice was taken Τα στοιχεία της λίστας άλλαξαν πριν ληφθεί η επιλογή @msg `answers` is larger than 1 MiB το `answers` είναι μεγαλύτερο από 1 MiB @msg `answers[{i}]` {e} το `answers[{i}]` {e} @msg must be an object with `kind` and `value` πρέπει να είναι αντικείμενο με `kind` και `value` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5cc8d86fdf..6c79382ae8 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5055,6 +5055,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg `answers` must be a list of answers `answers` debe ser una lista de respuestas @msg `answers` has more than {MAX_ANSWERS} answers `answers` tiene más de {MAX_ANSWERS} respuestas @msg {MAX_WAITING} script palette events already wait; this one was not kept ya esperan {MAX_WAITING} eventos de paletas de scripts; este no se ha conservado +@msg The list's items changed before the choice was taken Los elementos de la lista cambiaron antes de que se tomara la elección @msg `answers` is larger than 1 MiB `answers` ocupa más de 1 MiB @msg must be an object with `kind` and `value` debe ser un objeto con `kind` y `value` @msg must have exactly `kind` and `value` debe tener exactamente `kind` y `value` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1205c1dc9d..3a223923e4 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5296,6 +5296,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg `answers` must be a list of answers `answers` on oltava vastausten luettelo @msg `answers` has more than {MAX_ANSWERS} answers kohteessa `answers` on yli {MAX_ANSWERS} vastausta @msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} skriptipalettien tapahtumaa odottaa jo; tätä ei säilytetty +@msg The list's items changed before the choice was taken Luettelon kohteet muuttuivat ennen kuin valinta otettiin vastaan @msg `answers` is larger than 1 MiB `answers` on suurempi kuin 1 MiB @msg must be an object with `kind` and `value` on oltava objekti, jossa on `kind` ja `value` @msg must have exactly `kind` and `value` siinä on oltava täsmälleen `kind` ja `value` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index dbdca9ca76..0560264b7c 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8854,6 +8854,7 @@ breakText Glyphs Glyphes @msg `answer` for this {kind} dialog must be one of: {_1} `answer` pour cette boîte de dialogue {kind} doit valoir l’une de ces valeurs : {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` contient plus de {MAX_ANSWERS} réponses @msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} événements de palettes de script attendent déjà, celui-ci n’a donc pas été conservé +@msg The list's items changed before the choice was taken Les éléments de la liste ont changé avant que le choix soit pris en compte @msg `answers` is larger than 1 MiB `answers` dépasse 1 Mio @msg `answers` must be a list of answers `answers` doit être une liste de réponses @msg `artboard` must be the index of an artboard of the document `artboard` doit être l’indice d’un plan de travail du document diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 8c5e1f5602..d600eda164 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7729,6 +7729,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg `answers` must be a list of answers `answers` उत्तरों की सूची होनी चाहिए @msg `answers` has more than {MAX_ANSWERS} answers `answers` में {MAX_ANSWERS} से अधिक उत्तर हैं @msg {MAX_WAITING} script palette events already wait; this one was not kept स्क्रिप्ट पैलेट की {MAX_WAITING} घटनाएँ पहले से प्रतीक्षा में हैं; यह नहीं रखी गई +@msg The list's items changed before the choice was taken चुनाव लिए जाने से पहले सूची के आइटम बदल गए @msg `answers` is larger than 1 MiB `answers` 1 MiB से बड़ा है @msg `answers[{i}]` {e} `answers[{i}]`: {e} @msg must be an object with `kind` and `value` `kind` और `value` वाला ऑब्जेक्ट होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 6f7ce5a4ca..10ec8d74fc 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8858,6 +8858,7 @@ breakText Glyphs Glifák @msg `answer` for this {kind} dialog must be one of: {_1} `answer`: ennél a párbeszédablaknál ({kind}) ezek egyike kell: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers`: több mint {MAX_ANSWERS} választ tartalmaz @msg {MAX_WAITING} script palette events already wait; this one was not kept már {MAX_WAITING} parancsfájlpaletta-esemény várakozik; ez nem lett megtartva +@msg The list's items changed before the choice was taken A lista elemei megváltoztak, mielőtt a választás érvénybe lépett @msg `answers` is larger than 1 MiB `answers`: nagyobb 1 MiB-nál @msg `answers` must be a list of answers `answers`: válaszok listája kell @msg `artboard` must be the index of an artboard of the document `artboard`: a dokumentum egyik rajztáblájának indexe kell diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 25e340bec0..50c3eeec25 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -134,6 +134,7 @@ @msg `answers` must be a list of answers `answers` harus berupa daftar jawaban @msg `answers` has more than {MAX_ANSWERS} answers `answers` berisi lebih dari {MAX_ANSWERS} jawaban @msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} peristiwa palet skrip sudah menunggu; yang ini tidak disimpan +@msg The list's items changed before the choice was taken Item daftar berubah sebelum pilihan diterima @msg `answers` is larger than 1 MiB `answers` lebih besar dari 1 MiB @msg must be an object with `kind` and `value` harus berupa objek dengan `kind` dan `value` @msg must have exactly `kind` and `value` harus memiliki tepat `kind` dan `value` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ea73cf2b91..788dad1c7a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8468,6 +8468,7 @@ breakText Glyphs Glifi @msg `answer` for this {kind} dialog must be one of: {_1} `answer` per questa finestra di dialogo {kind} deve essere uno tra: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` ha più di {MAX_ANSWERS} risposte @msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} eventi delle palette di script sono già in attesa; questo non è stato conservato +@msg The list's items changed before the choice was taken Le voci dell'elenco sono cambiate prima che la scelta fosse acquisita @msg `answers` is larger than 1 MiB `answers` supera 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` è solo per un'esecuzione senza nessuno a cui chiedere: nell'app, la persona risponde a ogni finestra di dialogo @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` deve essere un numero intero da 1 a {_1} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 0b73565e9a..1ef4e34f52 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7294,6 +7294,7 @@ axis Y Axis Y 軸 @msg `answer` for this {kind} dialog must be one of: {_1} この {kind} ダイアログの `answer` には次のいずれかを指定してください: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` の回答が {MAX_ANSWERS} 個を超えています @msg {MAX_WAITING} script palette events already wait; this one was not kept スクリプトパレットのイベントがすでに {MAX_WAITING} 件待機しているため、このイベントは保持されませんでした +@msg The list's items changed before the choice was taken 選択が受け付けられる前にリストの項目が変更されました @msg `answers` is larger than 1 MiB `answers` が 1 MiB を超えています @msg `answers` must be a list of answers `answers` には回答のリストを指定してください @msg `artboard` must be the index of an artboard of the document `artboard` にはドキュメントのアートボードのインデックスを指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 541d871302..709bb0deea 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -177,6 +177,7 @@ @msg `answers[{i}]` {e} `answers[{i}]` {e} @msg `answers` has more than {MAX_ANSWERS} answers `answers` შეიცავს {MAX_ANSWERS}-ზე მეტ პასუხს @msg {MAX_WAITING} script palette events already wait; this one was not kept სკრიპტის პალიტრების {MAX_WAITING} მოვლენა უკვე ელოდება; ეს არ შენარჩუნდა +@msg The list's items changed before the choice was taken სიის ელემენტები შეიცვალა არჩევანის მიღებამდე @msg `answers` is larger than 1 MiB `answers` 1 MiB-ზე დიდია @msg `answers` must be a list of answers `answers` უნდა იყოს პასუხების სია @msg `artboard` must be the index of an artboard of the document `artboard` უნდა იყოს დოკუმენტის სამუშაო დაფის ინდექსი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 07bde95166..e306c15d66 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8626,6 +8626,7 @@ breakText Glyphs 글리프 @msg `answer` for this {kind} dialog must be one of: {_1} 이 {kind} 대화 상자의 `answer`은(는) 다음 중 하나여야 합니다: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers`에 응답이 {MAX_ANSWERS}개보다 많습니다 @msg {MAX_WAITING} script palette events already wait; this one was not kept 스크립트 팔레트 이벤트가 이미 {MAX_WAITING}개 대기 중이므로 이 이벤트는 보관되지 않았습니다 +@msg The list's items changed before the choice was taken 선택이 적용되기 전에 목록의 항목이 변경되었습니다 @msg `answers` is larger than 1 MiB `answers`이(가) 1 MiB보다 큽니다 @msg `answers` must be a list of answers `answers`은(는) 응답 목록이어야 합니다 @msg `artboard` must be the index of an artboard of the document `artboard`은(는) 문서에 있는 아트보드의 인덱스여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 9287dd44e3..93a35a622b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6494,6 +6494,7 @@ imageTrace Outline Contour @msg `answer` for this {kind} dialog must be one of: {_1} `answer` voor dit dialoogvenster {kind} moet een van de volgende zijn: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` heeft meer dan {MAX_ANSWERS} antwoorden @msg {MAX_WAITING} script palette events already wait; this one was not kept er wachten al {MAX_WAITING} gebeurtenissen van scriptpaletten; deze is niet bewaard +@msg The list's items changed before the choice was taken De items van de lijst zijn gewijzigd voordat de keuze werd overgenomen @msg `answers` is larger than 1 MiB `answers` is groter dan 1 MiB @msg `answers` must be a list of answers `answers` moet een lijst met antwoorden zijn @msg `artboard` must be the index of an artboard of the document `artboard` moet de index van een tekengebied van het document zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index fd7342da72..a89b52d6cd 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8671,6 +8671,7 @@ breakText Glyphs Glify @msg `answer` for this {kind} dialog must be one of: {_1} `answer` dla tego okna dialogowego {kind} musi mieć jedną z wartości: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` zawiera więcej niż {MAX_ANSWERS} odpowiedzi @msg {MAX_WAITING} script palette events already wait; this one was not kept czeka już {MAX_WAITING} zdarzeń palet skryptów; to zdarzenie nie zostało zachowane +@msg The list's items changed before the choice was taken Elementy listy zmieniły się, zanim wybór został przyjęty @msg `answers` is larger than 1 MiB `answers` ma rozmiar większy niż 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` służy tylko do uruchomienia, w którym nie ma kogo zapytać: w aplikacji na każde okno dialogowe odpowiada użytkownik @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` musi być liczbą całkowitą od 1 do {_1} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4aa2697468..24838d4c6b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9040,6 +9040,7 @@ swatch Yellow Green Verde-amarelado @msg `answer` for this {kind} dialog must be one of: {_1} `answer` para esta caixa de diálogo {kind} deve ser um de: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` tem mais de {MAX_ANSWERS} respostas @msg {MAX_WAITING} script palette events already wait; this one was not kept já há {MAX_WAITING} eventos de paletas de script aguardando; este não foi mantido +@msg The list's items changed before the choice was taken Os itens da lista mudaram antes de a escolha ser aplicada @msg `answers` is larger than 1 MiB `answers` tem mais de 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` é só para uma execução sem ninguém a quem perguntar: no app, a pessoa responde a cada caixa de diálogo @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` deve ser um número inteiro de 1 a {_1} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ac74d5747a..8bdecf2658 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5077,6 +5077,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg `answers` must be a list of answers `answers` должен быть списком ответов @msg `answers` has more than {MAX_ANSWERS} answers в `answers` больше {MAX_ANSWERS} ответов @msg {MAX_WAITING} script palette events already wait; this one was not kept уже ожидают {MAX_WAITING} событий палитр скриптов; это событие не сохранено +@msg The list's items changed before the choice was taken Элементы списка изменились до того, как выбор был принят @msg `answers` is larger than 1 MiB `answers` больше 1 МиБ @msg must be an object with `kind` and `value` должен быть объектом с `kind` и `value` @msg must have exactly `kind` and `value` должен содержать ровно `kind` и `value` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index dc74ea16ce..ea059da395 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4952,6 +4952,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg `answers` must be a list of answers `answers` måste vara en lista med svar @msg `answers` has more than {MAX_ANSWERS} answers `answers` har fler än {MAX_ANSWERS} svar @msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} händelser från skriptpaletter väntar redan; den här sparades inte +@msg The list's items changed before the choice was taken Listans objekt ändrades innan valet togs emot @msg `answers` is larger than 1 MiB `answers` är större än 1 MiB @msg `answers[{i}]` {e} `answers[{i}]` {e} @msg must be an object with `kind` and `value` måste vara ett objekt med `kind` och `value` diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 109ef0345a..07a1987942 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7670,6 +7670,7 @@ axis Y Axis Y ekseni @msg `answer` for this {kind} dialog must be one of: {_1} bu {kind} iletişim kutusu için `answer` şunlardan biri olmalıdır: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` içinde {MAX_ANSWERS} taneden fazla yanıt var @msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} betik paleti olayı zaten bekliyor; bu olay tutulmadı +@msg The list's items changed before the choice was taken Seçim alınmadan önce listenin öğeleri değişti @msg `answers` is larger than 1 MiB `answers` 1 MiB'tan büyük @msg `answers` must be a list of answers `answers` bir yanıt listesi olmalıdır @msg `artboard` must be the index of an artboard of the document `artboard`, belgedeki bir çalışma yüzeyinin dizini olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 20e6a222ab..f7b1ffc2a2 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8627,6 +8627,7 @@ breakText Glyphs Гліфи @msg `answer` for this {kind} dialog must be one of: {_1} `answer` для цього діалогового вікна ({kind}) має бути одним з: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` містить понад {MAX_ANSWERS} відповідей @msg {MAX_WAITING} script palette events already wait; this one was not kept уже очікують {MAX_WAITING} подій палітр скриптів; цю подію не збережено +@msg The list's items changed before the choice was taken Елементи списку змінилися до того, як вибір було прийнято @msg `answers` is larger than 1 MiB `answers` більший за 1 МіБ @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} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 173c74895c..4fa7e8ace1 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5576,6 +5576,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg `answers` must be a list of answers `answers` phải là một danh sách câu trả lời @msg `answers` has more than {MAX_ANSWERS} answers `answers` có hơn {MAX_ANSWERS} câu trả lời @msg {MAX_WAITING} script palette events already wait; this one was not kept đã có {MAX_WAITING} sự kiện bảng tập lệnh đang chờ; sự kiện này không được giữ lại +@msg The list's items changed before the choice was taken Các mục của danh sách đã thay đổi trước khi lựa chọn được nhận @msg `answers` is larger than 1 MiB `answers` lớn hơn 1 MiB @msg must be an object with `kind` and `value` phải là một đối tượng có `kind` và `value` @msg must have exactly `kind` and `value` phải có đúng `kind` và `value` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 129b2fff68..863ae243df 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8677,6 +8677,7 @@ breakText Glyphs 字形 @msg `answer` for this {kind} dialog must be one of: {_1} 此 {kind} 对话框的 `answer` 必须是以下之一:{_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` 中的回答超过 {MAX_ANSWERS} 个 @msg {MAX_WAITING} script palette events already wait; this one was not kept 已有 {MAX_WAITING} 个脚本面板事件在等待;此事件未保留 +@msg The list's items changed before the choice was taken 在采用选择之前,列表的项目已更改 @msg `answers` is larger than 1 MiB `answers` 大于 1 MiB @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} 之间的整数 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b11084d879..2d69c7b869 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8622,6 +8622,7 @@ breakText Glyphs 字符 @msg `answer` for this {kind} dialog must be one of: {_1} 此 {kind} 對話框的 `answer` 必須是下列其中之一:{_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` 的答案超過 {MAX_ANSWERS} 個 @msg {MAX_WAITING} script palette events already wait; this one was not kept 已有 {MAX_WAITING} 個指令碼面板事件在等待;此事件未保留 +@msg The list's items changed before the choice was taken 在採用選擇之前,清單的項目已變更 @msg `answers` is larger than 1 MiB `answers` 大於 1 MiB @msg `answers` must be a list of answers `answers` 必須是答案清單 @msg `artboard` must be the index of an artboard of the document `artboard` 必須是文件中某個工作區域的索引 diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 877548d602..b02fc382b2 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -28,10 +28,16 @@ fn run_to_end(app: &mut VectorcraftApp) { /// One headless frame in which `f` runs. → whether the frame asked for the next one at once. fn frame(ctx: &egui::Context, f: impl FnMut(&mut egui::Ui)) -> bool { + frame_delay(ctx, f).is_zero() +} + +/// One headless frame in which `f` runs. → how long until the frame asked for the next one; +/// `Duration::MAX` when it asked for none. +fn frame_delay(ctx: &egui::Context, f: impl FnMut(&mut egui::Ui)) -> std::time::Duration { let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, f); out.textures_delta.clear(); - out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.repaint_delay.is_zero()) + out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) } #[test] @@ -98,15 +104,15 @@ fn a_click_waiting_for_an_open_undo_group_asks_for_no_frames_and_runs_after_it() let ctx = egui::Context::default(); frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])); assert_eq!(app.session.script_palette_events_waiting(), 1); - let mut asks = true; + let mut delay = std::time::Duration::ZERO; for _ in 0..5 { app.begin_host_iteration(); - asks = frame(&ctx, |ui| app.tick(ui.ctx())); - if !asks { + delay = frame_delay(&ctx, |ui| app.tick(ui.ctx())); + if delay == std::time::Duration::MAX { break; } } - assert!(!asks, "the waiting click asks for no frames while the undo group is open"); + assert_eq!(delay, std::time::Duration::MAX, "the waiting click asks for no frames, now or later, while the undo group is open"); assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits"); app.run("edit.undoGroup.end", json!({})).unwrap(); app.begin_host_iteration(); diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 21fbd0c785..d3e6069f16 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -461,6 +461,32 @@ fn a_queued_click_reaches_its_button_after_a_handler_adds_a_control_before_it() assert_eq!(log(&app), json!([[1, "typed"]])); } +#[test] +fn a_queued_list_choice_is_not_given_after_a_handler_changed_the_list() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['a', 'b']); var swap = w.add('button', undefined, 'Swap'); \ + w.add('button', undefined, 'OK'); swap.onClick = function () { l.removeAll(); l.add('item', 'x'); l.add('item', 'y'); }; \ + vc.log([w.show(), String(l.selection)]);", + ); + assert!(until_window(&mut app)); + // A click on Swap, then a choice in the list as it was before Swap's handler ran, both given + // in one frame. + let swap = json!({"event": "click", "control": 2, "value": null}); + let choice = json!({"event": "change", "control": 1, "value": 1, "list": {"items": ["a", "b"], "revision": 2.0}}); + app.ui.dialog.as_mut().unwrap().fields.insert("queued".into(), json!([swap, choice])); + frame(&mut app, Vec::new()); + assert!(until_window(&mut app), "the script takes the click and waits again"); + assert_eq!(app.session.script_window().unwrap().nodes[1].items, ["x", "y"]); + frame(&mut app, Vec::new()); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("queued"), "the choice left the line"); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, "null"]]), "the choice for the old items was not given"); +} + #[test] fn continue_on_the_growth_question_shows_the_dialog_again_with_its_queued_click_and_typed_text() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 2bc012fe73..fef4f78655 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2983,7 +2983,8 @@ the same controls, handlers and limits: A palette also closes when `script.engine.drop` drops its engine, when its engine ends with an internal error, and when the session ends. The palette shows its controls as `show()`, `add()`, each event's handlers and each run of its engine leave them; a run that a limit or `script.stop` ended can leave it showing them as they were. - A handler's run reads and writes the files the person allowed the script that first showed the palette. + A handler's run reads and writes the files the person allowed the script that first showed the palette with + Always. A file allowed once stays with the run whose dialog allowed it, as for any later run. - Each click, change or close the person gives a palette runs its handler as a run of its own in the palette's engine, with its own report and, when it changes a document, its own Run Script undo step. While another run goes on, the event waits and runs after it; events run one at a time, oldest first. While an event waits, a @@ -3006,7 +3007,9 @@ waitingLimit: 64}`. `script.palette.event {palette, event, control?, value?}` gi `change` or a `close`, with `control` and `value` as in a `window` answer's step (`control` can also be a control's index). In the app it returns `{waiting: true, merged, waitingEvents}`, and the handler's report is later in `ui.inspect`'s `scriptReport`. With nobody to ask, it runs the waiting events and returns the report of this one, -or its error. A hidden palette, a disabled or hidden control, and a control that cannot take the event are errors. +or its error; an event whose run cannot begin ends it with that error, and the events after it keep waiting. A +hidden palette, a disabled or hidden control, and a control that cannot take the event are errors, and with nobody +to ask so is an event while an undo group is open. ```sh vectorcraft-cli run --cmd script.run --params '{"source": "#targetengine tools\nvar p = new Window(\"palette\", \"Tools\"); var go = p.add(\"button\", undefined, \"Add\"); go.onClick = function () { vc.run(\"shape.rectangle\", {x: 0, y: 0, width: 20, height: 20}); }; p.show();"}' From f05ec9a0906db1895c6f54609a251c8150bb9b23 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 21:36:00 -0800 Subject: [PATCH 07/34] Scripts: a palette event finds its control by its place, and a run at its dialog idles - script.palette.event's params text lists `control` and `value` with their notes in parentheses, so the description reads as a params object again. - A palette handler's run gets the place of the clicked or changed control from the host and gives the event to the control at that place in the palette as it is then. A getter read while the palette is described can add a control before it; the event no longer goes to the control that took its index. An event whose place holds no control is an error. - While a run waits at its ScriptUI dialog, the app asks for no frames; the pass that gives the dialog's event asks for the next one, and so does a frame that handles a control request while a run goes on, such as `ui.dialog.confirm` answering the dialog. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/palettes.rs | 2 +- crates/engine/src/script/scriptui.rs | 10 ++- crates/js/src/scriptui.rs | 35 +++++++++- crates/js/src/scriptui_tests.rs | 19 +++++ crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/app/control.rs | 4 ++ crates/ui-egui/src/dialogs/script_window.rs | 3 + crates/ui-egui/src/tests/script_window.rs | 77 +++++++++++++++++++++ 9 files changed, 146 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 349b46b28f..28a05598ea 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Script Palette Event", [], None, - "{palette: an id script.palettes lists, event: click|change|close, control?: a control's index, or its name or text (click and change), value?: an edit field's text, a slider's number, or a list's item index or null (change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; while it waits, another click on the same control, change of it or close of the same palette takes its place with the newer value, and a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", + "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; while it waits, another click on the same control, change of it or close of the same palette takes its place with the newer value, and a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", always, palette_event ), diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index e7de94a1bf..673fcf5714 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -65,7 +65,7 @@ pub(crate) struct Queued { /// Where the control of a click or a change sits in the palette ([`ScriptUiDialog::place_of`]), /// by which the event finds its control again when a run adds controls before it; empty for a /// close. - place: Vec, + pub(crate) place: Vec, /// For a list's change, the list's items as the palette showed them when the event was given and /// the list's revision then ([`super::scriptui::UiNode::revision`]), which the run checks the list /// still has. diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index fd3bda32a4..bb96c2771d 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -773,13 +773,17 @@ fn palette_close(host: &Host, args: &[Data]) -> Result { Ok(Data::Undefined) } -/// The event a palette handler's run is for, once: `{palette, event, id, value, items}`, as `show()` -/// takes a dialog's event with the palette's id added, and for a list's change the items the -/// palette showed; `null` for any other run, and after the first call. +/// The event a palette handler's run is for, once: `{palette, event, id, value, place, items}`, as +/// `show()` takes a dialog's event with the palette's id added, the place of a click's or a +/// change's control ([`ScriptUiDialog::place_of`]), which the run finds the control by, and for a +/// list's change the items the palette showed; `null` for any other run, and after the first call. fn palette_event(host: &Host, _: &[Data]) -> Result { let Some(queued) = host.palette_event.borrow_mut().take() else { return Ok(Data::Null) }; let Data::Object(mut fields) = queued.event.data() else { return Ok(Data::Null) }; fields.push(("palette".into(), Data::Number(queued.palette as f64))); + if !queued.place.is_empty() { + fields.push(("place".into(), Data::Array(queued.place.iter().map(|&k| Data::Number(k as f64)).collect()))); + } if let Some((items, revision)) = queued.list { fields.push(("items".into(), Data::Array(items.into_iter().map(Data::String).collect()))); fields.push(("revision".into(), Data::Number(revision))); diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index dac3e9d590..6e997aa2af 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -795,10 +795,23 @@ fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult= 1.0 && n.fract() == 0.0 && (n as usize) < count) { + let held = list_values(i, nodes)?; + // The host gives the control's place, which is found again in the palette as it is now: + // a getter read in the description may have added a control before it. + let at = match slot(i, ev, "place")? { + Value::Object(place) => { + let control = control_at_place(i, win, place)?; + control.and_then(|c| held.iter().position(|v| v.as_object() == Some(c))) + } + _ => match slot(i, ev, "id")? { + Value::Number(n) if n >= 1.0 && n.fract() == 0.0 => Some(n as usize), + _ => None, + }, + }; + let Some(at) = at.filter(|&n| n >= 1 && n < held.len()) else { return Err(error(i, "a palette event names a control the palette no longer holds")); - } + }; + set_slot(i, ev, "id", Value::Number(at as f64))?; take_event(i, win, nodes, ev, &event, None)?; } Ok(Value::Undefined) @@ -807,6 +820,22 @@ fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult JsResult> { + let mut at = win; + for k in list_values(i, place)? { + let Value::Number(k) = k else { return Ok(None) }; + if k < 0.0 || k.fract() != 0.0 { + return Ok(None); + } + let Some(kid) = kids_of(i, at)?.get(k as usize).and_then(Value::as_object) else { return Ok(None) }; + at = kid; + } + Ok((at != win).then_some(at)) +} + fn host_fn(i: &mut Interp, name: &str) -> JsResult { let host = classes(i)?.host; i.get_value(&Value::Object(host), &key(name)) diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index f9be03af3b..c6ed56abdb 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -530,6 +530,25 @@ fn a_palette_list_change_throws_when_an_item_s_text_getter_replaces_the_items() assert_eq!(r.run("[reads, got.join()].join()").unwrap(), JsValue::String("2,".into())); } +#[test] +fn a_palette_event_finds_its_control_by_its_place() { + let placed = |id: usize, place: &[f64]| { + let Data::Object(mut fields) = palette_event(1.0, click(id)) else { return Data::Null }; + fields.push(("place".into(), Data::Array(place.iter().map(|&k| Data::Number(k)).collect()))); + Data::Object(fields) + }; + // The host's index 1 is the group, where a control a getter added would have moved the button; + // the place is the button's, the second control of the palette. + let (mut r, _) = palette_realm(vec![placed(1, &[1.0]), placed(2, &[2.0])]); + r.run("var p = new Window('palette'); var g = p.add('group'); var b = p.add('button', undefined, 'Go'); var clicks = 0; b.onClick = function () { clicks++; }; p.show();") + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(1.0), "the click reaches the control at its place"); + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette event names a control the palette no longer holds".into()), "no control at the place"); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(1.0)); +} + #[test] fn a_palette_s_visible_follows_hide_and_show() { let (mut r, _) = palette_realm(Vec::new()); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 7cc5524c25..b24b69f419 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -378,10 +378,12 @@ impl VectorcraftApp { if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() + && self.session.script_window().is_none() && self.session.script_picker().is_none() { // A script in `$.sleep` goes on when its time is up; until then the app can idle. A // script at a file dialog goes on when the dialog answers, and `picks::poll` looks for that. + // A script at its ScriptUI dialog goes on when the dialog gives it an event. match self.session.script_sleep_left() { Some(left) => ctx.request_repaint_after(left), None => ctx.request_repaint(), diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 5ef64dfa3f..43e1cff7ed 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -120,6 +120,10 @@ impl VectorcraftApp { if handled == control::MAX_CONTROL_REQUESTS_PER_FRAME { // Leave later requests on the channel and schedule another frame to serve them. ctx.request_repaint(); + } else if handled > 0 && self.session.script_running() { + // A request may have answered the dialog a run waits at, which the app idles for: the + // next frame takes the answer and the run's next slice. + ctx.request_repaint(); } self.control_rx = Some(rx); } diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 343f6c27d3..78e130bab2 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -158,6 +158,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc } d.fields.extend(fields); } + // The event lets the run go on, which the app idles for while it waits: the next frame takes + // the run's next slice. + ui.ctx().request_repaint(); DialogAction::Confirm } diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index d3e6069f16..45bb4db50e 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -461,6 +461,83 @@ fn a_queued_click_reaches_its_button_after_a_handler_adds_a_control_before_it() assert_eq!(log(&app), json!([[1, "typed"]])); } +#[test] +fn a_run_waiting_at_its_dialog_asks_for_no_frames() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + let ctx = egui::Context::default(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let mut delay = std::time::Duration::ZERO; + for _ in 0..5 { + app.begin_host_iteration(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| app.tick(ui.ctx())); + out.textures_delta.clear(); + delay = out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay); + if delay == std::time::Duration::MAX { + break; + } + } + assert_eq!(delay, std::time::Duration::MAX, "the app idles until the person answers"); + assert!(app.session.script_window().is_some(), "the run still waits at its dialog"); +} + +#[test] +fn a_control_request_while_a_run_waits_at_its_dialog_asks_for_the_next_frame() { + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = app().with_control(rx); + start(&mut app, &format!("{FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + let ctx = egui::Context::default(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let drain = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| app.drain_control(ui.ctx())); + out.textures_delta.clear(); + out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) + }; + // A new context asks for a frame or two of its own first. + let mut settled = false; + for _ in 0..10 { + if !drain(&mut app).is_zero() { + settled = true; + break; + } + } + assert!(settled, "nothing asks for a frame while the run waits"); + // What MCP's `answer_dialog` sends, which a later pass gives the run. + let (req, _reply) = crate::control::ControlRequest::new("ui.dialog.confirm", json!({})); + tx.send(req).unwrap(); + let delay = drain(&mut app); + assert!(delay.is_zero(), "the answer is taken in the next frame: {delay:?}"); +} + +#[test] +fn a_pass_that_gives_the_dialog_s_queued_event_asks_for_the_next_frame() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + let ctx = CTX.with(Clone::clone); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let pass = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) + }; + // The focused field's cursor blink asks for a later frame once the dialog has settled. + let mut settled = false; + for _ in 0..40 { + if !pass(&mut app).is_zero() { + settled = true; + break; + } + } + assert!(settled, "the dialog stops asking for the very next frame while nothing happens in it"); + // A click on Bold that waited in line behind a typed text. + app.ui.dialog.as_mut().unwrap().fields.insert("queued".into(), json!([{"event": "click", "control": 2, "value": null}])); + assert!(pass(&mut app).is_zero(), "the run the click let go on asks for its next slice"); + assert!(app.session.script_window().is_none(), "the run took the click and has not waited again yet"); +} + #[test] fn a_queued_list_choice_is_not_given_after_a_handler_changed_the_list() { let mut app = app(); From 8cc34c71a07a4ff759dd3206b410ea59e51e7b66 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 09:17:14 -0800 Subject: [PATCH 08/34] Scripts: a palette event is dropped once a getter or a handler closed the palette A palette event checks again, after the palette's description is read and after each handler is read or run, that the host still shows the palette under the id the event names. A getter or an earlier handler that closed the palette now stops the event, so no click or change reaches a closed palette, and a list change whose palette closed is dropped rather than refused. --- crates/js/src/scriptui.rs | 56 ++++++++++++++++++-- crates/js/src/scriptui_tests.rs | 62 +++++++++++++++++++++++ crates/ui-egui/src/tests/script_window.rs | 21 +++++++- 3 files changed, 133 insertions(+), 6 deletions(-) diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 6e997aa2af..e912e8a387 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -794,6 +794,10 @@ fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult JsResult) -> JsResult { + if keep.is_some() { + return Ok(true); + } + let id = slot(i, ev, "palette")?; + Ok(matches!((slot(i, win, PALETTE_ID)?, id), (Value::Number(a), Value::Number(b)) if a == b)) +} + +/// Calls control `c`'s handler `name` for the event `ev` when it has one and `win` still takes the +/// event once the handler has been read: a getter for `name` may have closed the palette. +/// → `None` when `win` no longer takes the event, otherwise `handler`'s answer. +fn event_handler(i: &mut Interp, win: ObjId, c: ObjId, ev: ObjId, keep: Option<&[Value]>, name: &str) -> JsResult>> { + if !still_takes(i, win, ev, keep)? { + return Ok(None); + } + let f = i.get_value(&Value::Object(c), &key(name))?; + if !still_takes(i, win, ev, keep)? { + return Ok(None); + } + if !i.is_callable(&f) { + return Ok(Some(None)); + } + i.call(&f, &Value::Object(c), &[]).map(|v| Some(Some(v))) +} + /// The control at `place` in `win` as it is now: the index of each control among its container's /// controls, from the window down, as the host counts places. `None` when the palette has no /// control there. @@ -975,7 +1007,8 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { /// A click or a change the host gave in `ev` for control `id` of `nodes` (a description's list of /// elements): the control takes it and its handler runs. A dialog's button without `onClick` asks /// to close it with 1 when it is the default element and 2 when it is the cancel element, which -/// `keep` (`show()`'s kept values) names; a palette has no `keep`. +/// `keep` (`show()`'s kept values) names; a palette has no `keep`. No handler of a palette runs +/// once a getter, a setter or an earlier handler of the event closed the palette. fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, keep: Option<&[Value]>) -> JsResult<()> { let id = match slot(i, ev, "id")? { Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => n as usize, @@ -1003,7 +1036,10 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, } i.put(c, key("value"), Value::Bool(true), true)?; } - if handler(i, c, "onClick")?.is_none() + let Some(ran) = event_handler(i, win, c, ev, keep, "onClick")? else { + return Ok(()); + }; + if ran.is_none() && kind == "button" && let Some(keep) = keep { @@ -1019,11 +1055,15 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, match kind.as_str() { "edittext" => { i.put(c, key("text"), value, true)?; - handler(i, c, "onChanging")?; + if event_handler(i, win, c, ev, keep, "onChanging")?.is_none() { + return Ok(()); + } } "slider" => { i.put(c, key("value"), value, true)?; - handler(i, c, "onChanging")?; + if event_handler(i, win, c, ev, keep, "onChanging")?.is_none() { + return Ok(()); + } } _ => { let n = match value { @@ -1050,6 +1090,11 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, Value::Number(r) => r != number_slot(i, c, REVISION)?, _ => false, }; + // An item's text getter may have closed the palette, and its `onClose` + // may have changed the list: the event is then dropped, not refused. + if !still_takes(i, win, ev, keep)? { + return Ok(()); + } if revised || !same || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { return Err(error(i, "a palette's list changed before the person's choice was taken")); } @@ -1058,7 +1103,8 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, set_slot(i, c, SELECTION, Value::Number(n))?; } } - handler(i, c, "onChange")?; + // `onChanging` may have closed the palette. + event_handler(i, win, c, ev, keep, "onChange")?; } _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), } diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index c6ed56abdb..063d02a2af 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -549,6 +549,68 @@ fn a_palette_event_finds_its_control_by_its_place() { assert_eq!(r.run("clicks").unwrap(), JsValue::Number(1.0)); } +#[test] +fn a_palette_event_does_not_run_a_handler_once_a_getter_closed_the_palette() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run( + "var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var b = p.add('button', undefined, 'Go'); \ + var clicks = 0; b.onClick = function () { clicks++; }; var armed = false; \ + Object.defineProperty(label, 'text', {get: function () { if (armed) { armed = false; p.close(); } return 'idle'; }}); p.show();", + ) + .unwrap(); + // The event reads the label's text for the palette's description, which closes the palette. + r.run("armed = true; Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(0.0), "the click is not given to a closed palette"); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); +} + +#[test] +fn a_palette_list_change_does_not_run_on_change_once_an_item_s_text_getter_closed_the_palette() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The event reads the first item's text twice: for the palette's description, then to compare + // it with the items the person saw. The second read closes the palette. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ + Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.close(); } return 'a'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("none".into())); + assert_eq!(r.run("[reads, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("2,,null".into())); +} + +#[test] +fn a_palette_event_does_not_run_a_handler_whose_getter_closed_the_palette() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; \ + Object.defineProperty(b, 'onClick', {get: function () { reads++; p.close(); return function () { clicks++; }; }}); p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("[reads, clicks].join()").unwrap(), JsValue::String("1,0".into()), "the handler read from a closed palette does not run"); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); +} + +#[test] +fn a_palette_list_change_is_dropped_once_an_item_s_text_getter_closed_the_palette_and_on_close_changed_the_list() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The second read of the first item's text closes the palette, and its `onClose` adds an item. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ + p.onClose = function () { l.add('item', 'c'); }; \ + Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.close(); } return 'a'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("none".into()), "the event for a closed palette is dropped without an error"); + assert_eq!(r.run("[reads >= 2, l.items.length, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("true,3,,null".into())); +} + #[test] fn a_palette_s_visible_follows_hide_and_show() { let (mut r, _) = palette_realm(Vec::new()); diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 45bb4db50e..ed94fdde69 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -551,7 +551,7 @@ fn a_queued_list_choice_is_not_given_after_a_handler_changed_the_list() { // A click on Swap, then a choice in the list as it was before Swap's handler ran, both given // in one frame. let swap = json!({"event": "click", "control": 2, "value": null}); - let choice = json!({"event": "change", "control": 1, "value": 1, "list": {"items": ["a", "b"], "revision": 2.0}}); + let choice = json!({"event": "change", "control": 1, "value": 1, "place": [0], "list": {"items": ["a", "b"], "revision": 2.0}}); app.ui.dialog.as_mut().unwrap().fields.insert("queued".into(), json!([swap, choice])); frame(&mut app, Vec::new()); assert!(until_window(&mut app), "the script takes the click and waits again"); @@ -564,6 +564,25 @@ fn a_queued_list_choice_is_not_given_after_a_handler_changed_the_list() { assert_eq!(log(&app), json!([[1, "null"]]), "the choice for the old items was not given"); } +#[test] +fn a_queued_list_choice_is_given_while_its_list_is_unchanged() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['a', 'b']); w.add('button', undefined, 'OK'); \ + vc.log([w.show(), String(l.selection)]);", + ); + assert!(until_window(&mut app)); + let choice = json!({"event": "change", "control": 1, "value": 1, "place": [0], "list": {"items": ["a", "b"], "revision": 2.0}}); + app.ui.dialog.as_mut().unwrap().fields.insert("queued".into(), json!([choice])); + frame(&mut app, Vec::new()); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("queued"), "the choice left the line"); + assert!(until_window(&mut app), "the script takes the choice and waits again"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, "b"]]), "the choice for the same items was given"); +} + #[test] fn continue_on_the_growth_question_shows_the_dialog_again_with_its_queued_click_and_typed_text() { let mut app = app(); From 73394611d102f04fda4fd3061f7769d831885890 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 13:20:02 -0800 Subject: [PATCH 09/34] Scripts: ScriptUI windows, groups and panels have update() Window.update() was missing, so a palette handler that moved a progress bar and called update() ended with an error. The window-object reference describes update() as redrawing the window and taking the person's waiting events, so that a Cancel button can stop a long loop (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). - update() on a shown palette, or on a group or panel in it, runs the handlers of the clicks, changes and closes that wait for the palettes of the run's engine, oldest first, so a loop that calls update() sees a Cancel button's onClick. Those events do not get runs of their own. - In the app, an update() in the script's own code then pauses the run so the app draws the palette, at most once every 16 ms of the run's time (VectorCraft's own interval). Only an update() that pauses gives the host the palette's controls, so a loop of many update() calls does not use up the run's host-call or bridge limits. An update() in a handler, a callback of a built-in function, a getter or a conversion, and any update() on the web, does not pause the run. - update() on the showing dialog, or a group or panel in it, runs without an error; the dialog shows a handler's changes when the handler returns. On a window that is not showing it throws an Error, and on a control that is not a container a TypeError. Whether a palette is showing comes from show() and hide(), not from its visible property. - docs/mcp.md and the progress-doc line describe update(). --- crates/engine/src/script/mod.rs | 24 ++++ crates/engine/src/script/palettes.rs | 73 +++++++---- crates/engine/src/script/scriptui.rs | 30 ++++- crates/engine/src/tests/script_palettes.rs | 105 +++++++++++++++- .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/js/src/scriptui.rs | 86 +++++++++++++ crates/js/src/scriptui_tests.rs | 117 ++++++++++++++++++ docs/mcp.md | 22 +++- docs/target-app-parity.md | 2 +- 9 files changed, 429 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index ef204e4582..2ea2f2aa71 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -108,6 +108,9 @@ pub const MAX_LOG_LINES: usize = 10_000; pub const MAX_LOG_BYTES: usize = 4 << 20; /// The most bytes of `args` given to one run, as JSON. pub const MAX_ARGS_BYTES: usize = 1 << 20; +/// The shortest run time between two ScriptUI `update()` calls that each end the slice, so the app +/// draws the window (VectorCraft's own value, about one frame). +const UPDATE_INTERVAL: std::time::Duration = std::time::Duration::from_millis(16); /// The `vc.run` calls one slice makes before the interface draws again. const SLICE_HOST_CALLS: u32 = 256; /// The bytes that may cross between a script and the host in one run. @@ -799,6 +802,8 @@ struct Host { started: Option, /// The time since [`Host::started`] at which a `$.sleep` ends. wake_at: Cell>, + /// The time since [`Host::started`] at which a ScriptUI `update()` last ended the slice. + drawn_at: Cell>, /// Set while a host function runs where the run can stop at the call ([`Realm::wait_flag`]). can_wait: Rc>, /// What the last `#strict` line of the file `$.evalFile` last gave set (`None` without one). @@ -997,6 +1002,24 @@ impl Host { Ok(()) } + /// A palette's `update()` in the script's own code: in the app, ends the slice so the palette is + /// drawn as the script left it, at most once per [`UPDATE_INTERVAL`] of the run's time. → + /// whether it does, and the palette's controls are to be given now. Without a clock (the web + /// build), and in a run with nobody to draw for, the palette is drawn when the slice or the run + /// ends for another reason. + fn update_drawn(&self) -> bool { + if !self.framed { + return false; + } + let Some(now) = self.elapsed() else { return false }; + if self.drawn_at.get().is_some_and(|t| now.saturating_sub(t) < UPDATE_INTERVAL) { + return false; + } + self.drawn_at.set(Some(now)); + self.pause.set(true); + true + } + /// The time left of a `$.sleep`, or none when the run is not asleep. fn asleep(&self) -> Option { let wake = self.wake_at.get()?; @@ -2081,6 +2104,7 @@ impl Session { kept_maps, started: clock(), wake_at: Cell::new(None), + drawn_at: Cell::new(None), can_wait: realm.wait_flag(), eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 673fcf5714..68c84e3f0d 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -8,7 +8,9 @@ //! own in the palette's engine, which takes the mutation lease like any other run: one event at a //! time, oldest first, each starting only once no run is going. While an event waits, another click //! on the same control, another change of it or another close of the same palette takes its place -//! in line, with the newer value, instead of waiting as well. +//! in line, with the newer value, instead of waiting as well. A palette's `update()` in a run of the +//! palette's engine takes the events that wait for that engine's palettes and runs their handlers in +//! that run instead ([`Palettes::take_for`]). //! //! A palette closes when its script calls `close()` or the person closes it, unless `onClose` //! returns `false`; when its engine is dropped or ends with an internal error; and with the session. @@ -188,33 +190,56 @@ impl Palettes { /// no longer has, or that the control can no longer take ([`scriptui::check_event`]), for /// example because a handler disabled or hid it, is dropped. fn next(&mut self) -> Option<(ScriptPalette, Queued)> { - while let Some(mut q) = self.waiting.pop_front() { - let Some(p) = self.list.iter().find(|p| p.id == q.palette && p.visible) else { continue }; - if let Some(c) = control_of(&mut q.event) { - let Some(at) = p.dialog.control_at(&q.place) else { continue }; - *c = at; + while let Some(q) = self.waiting.pop_front() { + if let Some(taken) = self.checked(q) { + return Some(taken); } - // A list's change whose list a run changed since goes to its run, which ends with the - // error that says so, when the list can still take a change: the choice is checked - // without its item, which the list may no longer have. - let list_changed = match (&q.event, &q.list) { - (UiEvent::Change(c, UiValue::Index(_)), Some((_, revision))) => { - p.dialog.nodes.get(*c).is_some_and(|n| n.revision != *revision).then_some(*c) - } - _ => None, - }; - if let Some(c) = list_changed { - if scriptui::check_event(&p.dialog, UiEvent::Change(c, UiValue::Index(None))).is_err() { - continue; - } - } else { - let Ok(event) = scriptui::check_event(&p.dialog, q.event) else { continue }; - q.event = event; - } - return Some((p.clone(), q)); } None } + + /// As [`Palettes::next`], for the palettes of the engine `engine` only: the events of other + /// engines' palettes keep their places in line. + fn next_of(&mut self, engine: &str) -> Option<(ScriptPalette, Queued)> { + loop { + let list = &self.list; + let at = self.waiting.iter().position(|q| list.iter().any(|p| p.id == q.palette && p.engine == engine))?; + let q = self.waiting.remove(at)?; + if let Some(taken) = self.checked(q) { + return Some(taken); + } + } + } + + /// The taken event `q` given to the control at its place in its palette, and that palette, or + /// `None` when it is dropped ([`Palettes::next`]). + fn checked(&self, mut q: Queued) -> Option<(ScriptPalette, Queued)> { + let p = self.list.iter().find(|p| p.id == q.palette && p.visible)?; + if let Some(c) = control_of(&mut q.event) { + *c = p.dialog.control_at(&q.place)?; + } + // A list's change whose list a run changed since goes to its run, which ends with the + // error that says so, when the list can still take a change: the choice is checked + // without its item, which the list may no longer have. + let list_changed = match (&q.event, &q.list) { + (UiEvent::Change(c, UiValue::Index(_)), Some((_, revision))) => { + p.dialog.nodes.get(*c).is_some_and(|n| n.revision != *revision).then_some(*c) + } + _ => None, + }; + if let Some(c) = list_changed { + scriptui::check_event(&p.dialog, UiEvent::Change(c, UiValue::Index(None))).ok()?; + } else { + q.event = scriptui::check_event(&p.dialog, q.event).ok()?; + } + Some((p.clone(), q)) + } + + /// The oldest waiting event for a palette of the engine `engine`, which a palette's `update()` + /// in a run of that engine takes and hands to the palette at once ([`Palettes::next_of`]). + pub(crate) fn take_for(&mut self, engine: &str) -> Option { + self.next_of(engine).map(|(_, q)| q) + } } /// `name` in a `#targetengine` line, quoted with a quote it does not hold. diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index bb96c2771d..e460408a51 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -38,6 +38,7 @@ 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; +use super::palettes::Queued; /// The largest size or place, in pixels, of a dialog or a control in it. pub const MAX_EXTENT: f32 = 8192.0; @@ -712,6 +713,8 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr ("paletteHide".into(), function(link, palette_hide)), ("paletteClose".into(), function(link, palette_close)), ("paletteEvent".into(), function(link, palette_event)), + ("paletteTake".into(), function(link, palette_take)), + ("paletteDraw".into(), function(link, palette_draw)), ]) } @@ -747,7 +750,7 @@ fn palette_show(host: &Host, args: &[Data]) -> Result { shown.map(|id| Data::Number(id as f64)).map_err(HostError::Range) } -/// The palette `id`'s controls as a handler or `add()` left them. +/// The palette `id`'s controls as a handler, `add()` or `update()` left them. fn palette_update(host: &Host, args: &[Data]) -> Result { let engine = palette_engine(host)?.to_string(); let dialog = described(host, args)?; @@ -757,6 +760,22 @@ fn palette_update(host: &Host, args: &[Data]) -> Result { Ok(Data::Undefined) } +/// A palette's `update()` in the script's own code asks whether the app draws the palette now +/// ([`Host::update_drawn`]). → `true` when it does, and the script then gives the palette's +/// controls through `paletteUpdate`. +fn palette_draw(host: &Host, _: &[Data]) -> Result { + palette_engine(host)?; + Ok(Data::Bool(host.update_drawn())) +} + +/// A palette's `update()` takes the oldest event the person gave a palette of the run's engine, +/// which no run has handled yet, as `paletteEvent` gives it; `null` when none waits. +fn palette_take(host: &Host, _: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + let taken = host.session.borrow_mut().script_palettes.take_for(&engine); + Ok(taken.map_or(Data::Null, event_data)) +} + fn palette_hide(host: &Host, args: &[Data]) -> Result { let engine = palette_engine(host)?.to_string(); if let Some(id) = palette_id(args.first()) { @@ -779,7 +798,12 @@ fn palette_close(host: &Host, args: &[Data]) -> Result { /// list's change the items the palette showed; `null` for any other run, and after the first call. fn palette_event(host: &Host, _: &[Data]) -> Result { let Some(queued) = host.palette_event.borrow_mut().take() else { return Ok(Data::Null) }; - let Data::Object(mut fields) = queued.event.data() else { return Ok(Data::Null) }; + Ok(event_data(queued)) +} + +/// The waiting event `queued` as a script takes it ([`palette_event`]). +fn event_data(queued: Queued) -> Data { + let Data::Object(mut fields) = queued.event.data() else { return Data::Null }; fields.push(("palette".into(), Data::Number(queued.palette as f64))); if !queued.place.is_empty() { fields.push(("place".into(), Data::Array(queued.place.iter().map(|&k| Data::Number(k as f64)).collect()))); @@ -788,7 +812,7 @@ fn palette_event(host: &Host, _: &[Data]) -> Result { fields.push(("items".into(), Data::Array(items.into_iter().map(Data::String).collect()))); fields.push(("revision".into(), Data::Number(revision))); } - Ok(Data::Object(fields)) + Data::Object(fields) } fn described(host: &Host, args: &[Data]) -> Result { diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index c432700fe6..eff97479d1 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -2,11 +2,13 @@ //! and run one at a time after it, the events that take a waiting one's place, `close()` and the //! close box, the engine's end, and the limits. +use std::time::Duration; + use serde_json::{Value, json}; use crate::script::palettes::{MAX_PALETTES, MAX_WAITING}; use crate::script::scriptui::PALETTE_NEEDS_ENGINE; -use crate::script::{DialogAnswer, UiEvent, Waiting}; +use crate::script::{DialogAnswer, TEST_ELAPSED, UiEvent, Waiting}; use crate::*; /// One open document with one rectangle. @@ -72,6 +74,107 @@ fn show_returns_at_once_and_the_palette_stays_after_the_run() { assert_eq!(changed["log"], json!(["change abc"])); } +#[test] +fn update_in_a_palette_s_handler_runs_and_the_palette_shows_the_last_value() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 10); \ + var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { for (var k = 1; k <= 10; k++) { bar.value = k; p.update(); } vc.log('done'); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": "Go"})).unwrap(); + assert_eq!(clicked["log"], json!(["done"]), "update() in the handler does not throw"); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["controls"][0]["value"].as_f64(), Some(10.0), "{listed}"); +} + +#[test] +fn update_outside_a_handler_pauses_the_run_so_the_app_draws_the_palette_at_most_once_per_interval() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + s.script_frames = true; + let source = "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); p.show(); \ + for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); }"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + let value = |s: &Session| s.script_palettes().first().map_or(0.0, |p| p.dialog.nodes[1].value); + for _ in 0..100 { + assert!(s.script_pump().is_none(), "the run pauses at the first update()"); + if value(&s) > 0.0 { + break; + } + } + let first = value(&s); + assert!(first > 0.0); + TEST_ELAPSED.set(Some(Duration::from_millis(16))); + assert!(s.script_pump().is_none(), "an update() a frame later pauses the run too"); + let second = value(&s); + assert!(second > first, "the palette shows the second update()"); + assert!(s.script_pump().expect("an update() within the same frame does not pause the run").is_ok()); + assert!(value(&s) > second); + TEST_ELAPSED.set(None); +} + +#[test] +fn update_hands_a_click_given_during_the_run_to_its_handler_so_cancel_stops_the_loop() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + s.script_frames = true; + let source = "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 100000); \ + var cancel = p.add('button', undefined, 'Cancel'); var stopped = false; cancel.onClick = function () { stopped = true; }; \ + p.show(); var k = 0; while (!stopped && k < 100000) { k++; bar.value = k; p.update(); } vc.log(stopped ? 'canceled' : 'ran out');"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + for _ in 0..100 { + if !s.script_palettes().is_empty() { + break; + } + assert!(s.script_pump().is_none(), "the run pauses at the first update()"); + } + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + let report = pump(&mut s).expect("the run ended").unwrap(); + assert_eq!(report["log"], json!(["canceled"]), "{report}"); + assert_eq!(s.script_palette_events_waiting(), 0, "the click was handled in the run, not left for a run of its own"); + TEST_ELAPSED.set(None); +} + +#[test] +fn update_in_a_handler_does_not_pause_the_run() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); \ + var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); } vc.log('done'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + let report = s.script_pump().expect("the handler's run ends without a pause after the handler").unwrap(); + assert_eq!(report["log"], json!(["done"])); + TEST_ELAPSED.set(None); +} + +#[test] +fn many_update_calls_within_one_interval_give_the_controls_once() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + let report = run_in_app( + &mut s, + "#targetengine progress\nvar names = []; for (var n = 0; n < 500; n++) { names.push('a long list item name ' + n); } \ + var p = new Window('palette'); var list = p.add('listbox', undefined, names); var bar = p.add('progressbar', undefined, 0, 1000); \ + p.show(); for (var k = 1; k <= 1000; k++) { bar.value = k; p.update(); }", + ); + let calls = report["hostCalls"].as_u64().unwrap(); + assert!(calls < 1000, "an update() the app does not draw costs no host call: {calls}"); + let bar = s.script_palettes()[0].dialog.nodes[2].value; + assert_eq!(bar, 1000.0, "the palette shows the last value once the run ends"); + TEST_ELAPSED.set(None); +} + #[test] fn a_later_run_in_the_engine_changes_what_the_palette_shows() { let mut s = one_doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 08badaae56..ba03106e4b 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -45,7 +45,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder Window alert confirm localize prompt toSource"), ("Window.", "__vcPaletteEvent length prototype"), - ("Window.prototype.", "add center close constructor findElement hide show"), + ("Window.prototype.", "add center close constructor findElement hide show update"), ("Object.prototype.", "toSource"), ("localize.", "length"), ("toSource.", "length"), diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index e912e8a387..2d2ccf2e9a 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -33,6 +33,14 @@ //! host's `paletteEvent` (`{palette, event, id, value}`, or `null`), gives it to that palette as a //! dialog takes one, and then gives `paletteUpdate` each palette's description; `add()` on a shown //! palette does the same for that palette, so the host's list of its controls stays in step. +//! `update()` on a shown palette, or on a `group` or a `panel` in one, takes each event that waits +//! for a palette of the run's engine from the host's `paletteTake` (as `paletteEvent` gives it, or +//! `null`) and gives it to its palette. Then, called from the script's own code (not from a +//! handler, a callback of a built-in function, a getter or a conversion), it asks the host's +//! `paletteDraw` whether the palette is drawn now, and when it is, gives `paletteUpdate` the +//! palette's description. On the showing dialog, or a group or panel in it, `update()` does +//! nothing more, and on a window that is not showing it throws an `Error`. A dialog takes the +//! person's events once the running handler returns. //! //! 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 @@ -77,6 +85,7 @@ const ITEMS: &str = "__vcItems"; const SELECTION: &str = "__vcSelection"; const LIST: &str = "__vcList"; const PALETTE_ID: &str = "__vcPaletteId"; +const SHOWN: &str = "__vcShown"; const IN_CLOSE: &str = "__vcInClose"; /// How many times a list's items were added or removed: a palette's waiting change of the list is /// for the items it had then. @@ -683,11 +692,76 @@ fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { if let Value::Number(id) = slot(i, o, PALETTE_ID)? { let f = host_fn(i, "paletteHide")?; i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + set_slot(i, o, SHOWN, Value::Bool(false))?; i.put(o, key("visible"), Value::Bool(false), true)?; } Ok(Value::Undefined) } +/// `update()` on a window: [`update_window`]. +fn update(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let own = own_code(i); + let (o, palette) = window_of(i, &this, "update")?; + update_window(i, o, palette, own)?; + Ok(Value::Undefined) +} + +/// Whether the native running now was called from the script's own code in a run that can pause, +/// as the host's functions find whether a run can wait. +fn own_code(i: &Interp) -> bool { + i.in_slice && i.reentry == 0 +} + +/// `update()` on a `group` or a `panel`: [`update_window`] for the window that holds it. +fn control_update(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let own = own_code(i); + let (o, kind) = element(i, &this, "update")?; + if !is_container(&kind) { + return Err(i.type_error("update: this is not a ScriptUI window or container")); + } + let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a container without its window".into())) }; + let palette = matches!(slot(i, win, KIND)?, Value::String(s) if s.to_rust_string() == "palette"); + update_window(i, win, palette, own)?; + Ok(Value::Undefined) +} + +/// `update()` on the window `win`. On a shown palette: hands each event that waits for a palette of +/// the run's engine to its palette ([`take_waiting`]), and then, from the script's own code (`own`), +/// gives the host the palette's controls when the host draws it now (`paletteDraw`). The showing +/// dialog's controls go to the host when its handler returns, since a handler runs to its end in +/// one slice. Whether a palette shows is the host's, not its `visible` property. A window that is +/// not showing throws. +fn update_window(i: &mut Interp, win: ObjId, palette: bool, own: bool) -> JsResult<()> { + let showing = if palette { slot(i, win, SHOWN)?.truthy() } else { classes(i)?.showing == Some(win) }; + if !showing { + return Err(error(i, "update: the window is not showing")); + } + if !palette { + return Ok(()); + } + take_waiting(i)?; + if !own || !slot(i, win, SHOWN)?.truthy() { + return Ok(()); + } + let f = host_fn(i, "paletteDraw")?; + if i.call(&f, &Value::Undefined, &[])?.truthy() { + update_palette(i, win)?; + } + Ok(()) +} + +/// Hands each event the host's `paletteTake` gives, oldest first, to its palette, until none waits. +fn take_waiting(i: &mut Interp) -> JsResult<()> { + let f = host_fn(i, "paletteTake")?; + loop { + let answer = i.call(&f, &Value::Undefined, &[])?; + if answer.as_object().is_none() { + return Ok(()); + } + deliver(i, answer)?; + } +} + fn set_palettes(i: &mut Interp, f: impl FnOnce(&mut Vec)) { if let Some(c) = i.script_ui.as_mut() { f(&mut c.palettes); @@ -705,6 +779,7 @@ fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { } if let Value::Number(id) = slot(i, win, PALETTE_ID)? { set_slot(i, win, PALETTE_ID, Value::Undefined)?; + set_slot(i, win, SHOWN, Value::Bool(false))?; set_palettes(i, |p| p.retain(|o| *o != win)); let f = host_fn(i, "paletteClose")?; i.call(&f, &Value::Undefined, &[Value::Number(id)])?; @@ -760,6 +835,7 @@ fn palette_shown(i: &mut Interp, keep: &[Value], id: Value) -> JsResult { if !classes(i)?.palettes.contains(&win) { set_palettes(i, |p| p.push(win)); } + set_slot(i, win, SHOWN, Value::Bool(true))?; i.put(win, key("visible"), Value::Bool(true), true)?; handler(i, win, "onShow")?; update_palette(i, win)?; @@ -773,6 +849,14 @@ fn palette_shown(i: &mut Interp, keep: &[Value], id: Value) -> JsResult { fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { let f = host_fn(i, "paletteEvent")?; let answer = i.call(&f, &Value::Undefined, &[])?; + deliver(i, answer)?; + Ok(Value::Undefined) +} + +/// Gives the host's event `answer` (`{palette, event, id, value, place}`, or anything else for +/// none) to its palette the way a dialog takes the person's event. An event for a palette that has +/// closed does nothing. +fn deliver(i: &mut Interp, answer: Value) -> JsResult { let Some(ev) = answer.as_object() else { return Ok(Value::Undefined) }; let mark = i.temp_roots.len(); i.temp_roots.push(answer.clone()); @@ -1422,6 +1506,7 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul method(i, window_proto, "close", close, 1)?; method(i, window_proto, "hide", hide, 0)?; method(i, window_proto, "center", nothing, 1)?; + method(i, window_proto, "update", update, 0)?; pausable_method(i, window_proto, "show", show, 0)?; method(i, control_proto, "add", add, 4)?; method(i, control_proto, "findElement", find_element, 1)?; @@ -1429,6 +1514,7 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul 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, control_proto, "update", control_update, 0)?; method(i, item_proto, "toString", item_to_string, 0)?; let index = native(i, "index", item_index, 0, NativeKind::Plain, false)?; i.define(item_proto, key("index"), Prop::Accessor { get: Some(index), set: None, flags: 0 })?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 063d02a2af..355faee1cf 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -380,6 +380,12 @@ type Calls = Rc>>; /// A realm with palette host functions: `paletteShow` gives ids from 1, and `paletteEvent` gives /// the events in `events`, in order, then `null`. fn palette_realm(events: Vec) -> (Realm, Calls) { + palette_realm_with(events, Vec::new(), Vec::new()) +} + +/// [`palette_realm`], whose `paletteTake` also gives the events in `taken`, in order, then `null`, +/// and whose `paletteDraw` gives the answers in `draws`, in order, then `false`. +fn palette_realm_with(events: Vec, taken: Vec, draws: Vec) -> (Realm, Calls) { let mut r = Realm::new(); r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); let calls: Calls = Rc::default(); @@ -403,6 +409,18 @@ fn palette_realm(events: Vec) -> (Realm, Calls) { Ok(Data::Number(id)) }); let event: HostFunction = Rc::new(move |_| Ok(events.borrow_mut().pop_front().unwrap_or(Data::Null))); + let taken = RefCell::new(VecDeque::from(taken)); + let c = calls.clone(); + let take: HostFunction = Rc::new(move |_| { + c.borrow_mut().push(("paletteTake".into(), 0.0)); + Ok(taken.borrow_mut().pop_front().unwrap_or(Data::Null)) + }); + let draws = RefCell::new(VecDeque::from(draws)); + let c = calls.clone(); + let draw: HostFunction = Rc::new(move |_| { + c.borrow_mut().push(("paletteDraw".into(), 0.0)); + Ok(Data::Bool(draws.borrow_mut().pop_front().unwrap_or(false))) + }); let none: HostFunction = Rc::new(|_| Err(HostError::Error("no dialog here".into()))); let items = vec![ ("open".into(), HostItem::Function(none.clone())), @@ -414,6 +432,8 @@ fn palette_realm(events: Vec) -> (Realm, Calls) { ("paletteHide".into(), HostItem::Function(record("paletteHide", 0))), ("paletteClose".into(), HostItem::Function(record("paletteClose", 0))), ("paletteEvent".into(), HostItem::Function(event)), + ("paletteTake".into(), HostItem::Function(take)), + ("paletteDraw".into(), HostItem::Function(draw)), ]; r.define_script_ui(items).unwrap(); (r, calls) @@ -467,6 +487,103 @@ fn closing_a_palette_runs_on_close_which_can_keep_it_open() { assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); } +fn count(calls: &Calls, name: &str) -> usize { + calls.borrow().iter().filter(|(n, _)| n == name).count() +} + +#[test] +fn update_in_the_script_s_own_code_gives_the_controls_only_when_the_host_draws_the_palette() { + let (mut r, calls) = palette_realm_with(Vec::new(), Vec::new(), vec![true, false, false, true]); + r.start( + "var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 4); p.show(); \ + for (var k = 1; k <= 4; k++) { bar.value = k; p.update(); }", + ) + .unwrap(); + while r.advance(1_000_000).unwrap() == Progress::Paused {} + assert_eq!(count(&calls, "paletteDraw"), 4, "each update() asks whether the palette is drawn"); + assert_eq!(count(&calls, "paletteUpdate"), 1 + 2, "show(), then only the update() calls the host draws"); +} + +#[test] +fn update_in_a_handler_neither_asks_to_draw_the_palette_nor_gives_its_controls() { + let (mut r, calls) = palette_realm_with(vec![palette_event(1.0, click(2))], Vec::new(), vec![true; 3]); + r.run( + "var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); } }; p.show();", + ) + .unwrap(); + let before = count(&calls, "paletteUpdate"); + r.start("Window.__vcPaletteEvent();").unwrap(); + while r.advance(1_000_000).unwrap() == Progress::Paused {} + assert_eq!(count(&calls, "paletteDraw"), 0, "a handler cannot pause, so its update() is not drawn"); + assert_eq!(count(&calls, "paletteUpdate"), before, "the handler's update() calls give the host no controls"); + r.refresh_script_ui().unwrap(); + assert_eq!(count(&calls, "paletteUpdate") - before, 1, "the controls go to the host once the run ends"); +} + +#[test] +fn update_hands_a_waiting_click_to_the_palette_so_a_cancel_button_stops_a_loop() { + let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(2))], Vec::new()); + let done = r + .run( + "var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 100); \ + var cancel = p.add('button', undefined, 'Cancel'); var stopped = false; \ + cancel.onClick = function () { stopped = true; }; p.show(); \ + var k = 0; while (!stopped && k < 100) { k++; bar.value = k; p.update(); } k + ':' + stopped", + ) + .unwrap(); + assert_eq!(done, JsValue::String("1:true".into()), "the first update() runs the click's onClick"); + assert!(count(&calls, "paletteTake") >= 2, "update() takes events until none waits"); +} + +#[test] +fn update_throws_for_a_window_that_is_not_showing() { + let (mut r, _, _) = realm(vec![click(12)]); + let source = format!( + "{FORM} var before = 'none'; try {{ w.update(); }} catch (e) {{ before = e.message; }} var during = 'none'; \ + ok.onClick = function () {{ w.update(); during = 'ran'; w.close(1); }}; [w.show(), before, during].join('|')" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("1|update: the window is not showing|ran".into())); + let (mut r, _) = palette_realm(Vec::new()); + let hidden = r + .run( + "var p = new Window('palette'); var log = []; try { p.update(); } catch (e) { log.push('before show'); } \ + p.show(); p.update(); p.hide(); try { p.update(); } catch (e) { log.push('hidden'); } log.join()", + ) + .unwrap(); + assert_eq!(hidden, JsValue::String("before show,hidden".into())); +} + +#[test] +fn update_on_a_showing_dialog_its_group_or_its_panel_runs_in_a_handler() { + let (mut r, _, _) = realm(vec![click(12)]); + let source = format!( + "{FORM} var done = 'none'; ok.onClick = function () {{ bar.value = 7; w.update(); g.update(); p.update(); done = 'ran'; w.close(1); }}; \ + [w.show(), done].join('|')" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("1|ran".into())); +} + +#[test] +fn update_follows_whether_the_host_shows_a_palette_not_its_visible_property() { + let (mut r, calls) = palette_realm_with(Vec::new(), Vec::new(), vec![true; 4]); + r.run("var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); p.show();").unwrap(); + let before = count(&calls, "paletteUpdate"); + r.start( + "var log = []; p.visible = false; p.update(); g.update(); log.push('shown'); \ + p.hide(); p.visible = true; try { p.update(); } catch (e) { log.push('hidden'); } \ + try { b.update(); } catch (e) { log.push(e.name); } log.join()", + ) + .unwrap(); + let log = loop { + if let Progress::Done(v) = r.advance(1_000_000).unwrap() { + break v; + } + }; + assert_eq!(log, JsValue::String("shown,hidden,TypeError".into())); + assert_eq!(count(&calls, "paletteUpdate") - before, 2, "the palette and its group each give the host the controls while it shows"); +} + #[test] fn a_palette_list_change_after_its_items_changed_throws() { let seen = |index: f64| { diff --git a/docs/mcp.md b/docs/mcp.md index fef4f78655..941a86437c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2918,8 +2918,15 @@ controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and s - 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. + (15 to start, 0 for a group), `findElement(name)` and `update()`. The dialog has `defaultElement`, + `cancelElement`, `close([result])`, `hide()` and `update()`. `center()`, `layout.layout()` and + `layout.resize()` do nothing. +- `update()` on the showing dialog, or on a group or panel in it, runs without an error and does nothing more: a handler + runs to its end before the app draws again, so the dialog shows the handler's changes when the handler + returns, and a progress bar that a handler moves shows only its last value. On a window that is not showing + it throws an `Error`, and on a control that is not a container it throws a `TypeError`. It does not take the + person's clicks or changes: the dialog takes them once the running handler returns, so a loop that waits for + a Cancel button's `onClick` to set a flag does not see the click. `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 @@ -2983,6 +2990,17 @@ the same controls, handlers and limits: A palette also closes when `script.engine.drop` drops its engine, when its engine ends with an internal error, and when the session ends. The palette shows its controls as `show()`, `add()`, each event's handlers and each run of its engine leave them; a run that a limit or `script.stop` ended can leave it showing them as they were. + `update()` on the palette, or on a group or panel in it, first runs the handlers of the clicks, changes and + closes that wait for the palettes of the run's engine, oldest first, so a Cancel button's `onClick` can stop + a loop that calls `update()` (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). + Those events do not wait for runs of their own. In the app, an `update()` in the script's own code then + pauses the run so the app draws the palette as it is, at most once every 16 ms of the run's time + (VectorCraft's own interval); an `update()` within the same 16 ms does not pause the run, and the app draws + its changes at the next pause or when the run ends. An `update()` in a handler, in a callback of a built-in + function such as `forEach`, in a getter or in a conversion does not pause the run, since the run cannot + pause there, and on the web `update()` does not pause the run; the app draws those changes when the run ends. + On a palette that `hide()` hid, or that is not shown, it throws an `Error`; setting the palette's `visible` + does not change this. A handler's run reads and writes the files the person allowed the script that first showed the palette with Always. A file allowed once stays with the run whose dialog allowed it, as for any later run. - Each click, change or close the person gives a palette runs its handler as a run of its own in the palette's diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c8f4bb0095..9919c099c6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1067,7 +1067,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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. 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`. - - Scripts: ScriptUI's `new Window("palette")` in a script with `#targetengine` shows a palette that stays open beside the documents after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going; a newer event for the same control takes a waiting one's place. A palette closes with `close()`, its close box, or the end of its engine or the session; at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.rs`. + - Scripts: ScriptUI's `new Window("palette")` in a script with `#targetengine` shows a palette that stays open beside the documents after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going; a newer event for the same control takes a waiting one's place. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes, so a Cancel button can stop a loop, and in the script's own code in the app pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. A palette closes with `close()`, its close box, or the end of its engine or the session; at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.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`). From 037a01b5210e2add20ed06eb608510faf31f0a22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 22:49:29 -0800 Subject: [PATCH 10/34] Scripts: update() checks each waiting palette event against the palette as handlers left it update() takes the events that wait for the run's palettes one at a time. Before each one, the host now gets every palette's controls as the script and the earlier handlers left them, as at the end of a run, so a click on a control that an earlier handler disabled, hid or removed runs no handler and is dropped. The new host function palettePending says whether an event still waits. An update() that a getter or a handler calls while events are being taken takes none itself; the update() already taking them goes on with the next one, instead of calling itself until a limit stops the run. Docs: docs/mcp.md palette bullet. --- crates/engine/src/script/palettes.rs | 6 ++++ crates/engine/src/script/scriptui.rs | 8 +++++ crates/engine/src/tests/script_palettes.rs | 26 ++++++++++++++++ crates/js/src/scriptui.rs | 34 ++++++++++++++++++-- crates/js/src/scriptui_tests.rs | 36 +++++++++++++++++++--- docs/mcp.md | 4 ++- 6 files changed, 107 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 68c84e3f0d..b06dae36fa 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -240,6 +240,12 @@ impl Palettes { pub(crate) fn take_for(&mut self, engine: &str) -> Option { self.next_of(engine).map(|(_, q)| q) } + + /// Whether an event waits for a palette of the engine `engine`, which [`Palettes::take_for`] + /// would then check and take. + pub(crate) fn waits_for(&self, engine: &str) -> bool { + self.waiting.iter().any(|q| self.list.iter().any(|p| p.id == q.palette && p.engine == engine)) + } } /// `name` in a `#targetengine` line, quoted with a quote it does not hold. diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index e460408a51..dc4bbf3bc5 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -714,6 +714,7 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr ("paletteClose".into(), function(link, palette_close)), ("paletteEvent".into(), function(link, palette_event)), ("paletteTake".into(), function(link, palette_take)), + ("palettePending".into(), function(link, palette_pending)), ("paletteDraw".into(), function(link, palette_draw)), ]) } @@ -776,6 +777,13 @@ fn palette_take(host: &Host, _: &[Data]) -> Result { Ok(taken.map_or(Data::Null, event_data)) } +/// Whether an event waits for a palette of the run's engine, which a palette's `update()` asks +/// before it gives the palettes' controls and takes the event with `paletteTake`. +fn palette_pending(host: &Host, _: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + Ok(Data::Bool(host.session.borrow().script_palettes.waits_for(&engine))) +} + fn palette_hide(host: &Host, args: &[Data]) -> Result { let engine = palette_engine(host)?.to_string(); if let Some(id) = palette_id(args.first()) { diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index eff97479d1..54de688f93 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -140,6 +140,32 @@ fn update_hands_a_click_given_during_the_run_to_its_handler_so_cancel_stops_the_ TEST_ELAPSED.set(None); } +#[test] +fn update_drops_a_waiting_click_on_a_control_an_earlier_handler_disabled() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + s.script_frames = true; + let source = "#targetengine progress\nvar p = new Window('palette'); var stop = p.add('button', undefined, 'Stop'); \ + var other = p.add('button', undefined, 'Other'); var stopped = false; var log = []; \ + stop.onClick = function () { stopped = true; other.enabled = false; log.push('stop'); }; \ + other.onClick = function () { log.push('other'); }; \ + p.show(); var k = 0; while (!stopped && k < 100000) { k++; p.update(); } vc.log(log.join());"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + for _ in 0..100 { + if !s.script_palettes().is_empty() { + break; + } + assert!(s.script_pump().is_none(), "the run pauses at the first update()"); + } + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + let report = pump(&mut s).expect("the run ended").unwrap(); + assert_eq!(report["log"], json!(["stop"]), "the click on the disabled button runs no handler: {report}"); + assert_eq!(s.script_palette_events_waiting(), 0, "the click on the disabled button is dropped"); + TEST_ELAPSED.set(None); +} + #[test] fn update_in_a_handler_does_not_pause_the_run() { TEST_ELAPSED.set(Some(Duration::ZERO)); diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 2d2ccf2e9a..4a13c7c835 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -35,7 +35,8 @@ //! palette does the same for that palette, so the host's list of its controls stays in step. //! `update()` on a shown palette, or on a `group` or a `panel` in one, takes each event that waits //! for a palette of the run's engine from the host's `paletteTake` (as `paletteEvent` gives it, or -//! `null`) and gives it to its palette. Then, called from the script's own code (not from a +//! `null`) and gives it to its palette, while the host's `palettePending` says one waits, giving +//! `paletteUpdate` each palette's description before each one. Then, called from the script's own code (not from a //! handler, a callback of a built-in function, a getter or a conversion), it asks the host's //! `paletteDraw` whether the palette is drawn now, and when it is, gives `paletteUpdate` the //! palette's description. On the showing dialog, or a group or panel in it, `update()` does @@ -104,6 +105,8 @@ pub(crate) struct Classes { selection_set: ObjId, showing: Option, palettes: Vec, + /// Whether an `update()` is taking the waiting events ([`take_waiting`]). + taking: bool, } impl Classes { @@ -750,10 +753,36 @@ fn update_window(i: &mut Interp, win: ObjId, palette: bool, own: bool) -> JsResu Ok(()) } -/// Hands each event the host's `paletteTake` gives, oldest first, to its palette, until none waits. +/// Hands each event the host's `paletteTake` gives, oldest first, to its palette, until none waits +/// (`palettePending`). Before each one the host gets every palette's controls as the script and the +/// handlers before it left them, as at the end of a run, and drops an event whose control has since +/// been disabled, hidden or removed. An `update()` that a getter or a handler calls meanwhile takes +/// no events: the `update()` already taking them goes on with the next one. fn take_waiting(i: &mut Interp) -> JsResult<()> { + if i.script_ui.as_ref().is_some_and(|c| c.taking) { + return Ok(()); + } + set_taking(i, true); + let r = take_each(i); + set_taking(i, false); + r +} + +fn set_taking(i: &mut Interp, taking: bool) { + if let Some(c) = i.script_ui.as_mut() { + c.taking = taking; + } +} + +/// [`take_waiting`]'s loop. +fn take_each(i: &mut Interp) -> JsResult<()> { + let pending = host_fn(i, "palettePending")?; let f = host_fn(i, "paletteTake")?; loop { + if !i.call(&pending, &Value::Undefined, &[])?.truthy() { + return Ok(()); + } + update_palettes(i)?; let answer = i.call(&f, &Value::Undefined, &[])?; if answer.as_object().is_none() { return Ok(()); @@ -1496,6 +1525,7 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul selection_set, showing: None, palettes: Vec::new(), + taking: false, }); let window = native(i, "Window", window_ctor, 4, NativeKind::Plain, true)?; constructor(i, "Window", window, window_proto)?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 355faee1cf..4dcf1a3ed5 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -384,7 +384,8 @@ fn palette_realm(events: Vec) -> (Realm, Calls) { } /// [`palette_realm`], whose `paletteTake` also gives the events in `taken`, in order, then `null`, -/// and whose `paletteDraw` gives the answers in `draws`, in order, then `false`. +/// whose `palettePending` says whether any of them is left, and whose `paletteDraw` gives the +/// answers in `draws`, in order, then `false`. fn palette_realm_with(events: Vec, taken: Vec, draws: Vec) -> (Realm, Calls) { let mut r = Realm::new(); r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); @@ -409,11 +410,17 @@ fn palette_realm_with(events: Vec, taken: Vec, draws: Vec) -> Ok(Data::Number(id)) }); let event: HostFunction = Rc::new(move |_| Ok(events.borrow_mut().pop_front().unwrap_or(Data::Null))); - let taken = RefCell::new(VecDeque::from(taken)); + let taken = Rc::new(RefCell::new(VecDeque::from(taken))); let c = calls.clone(); + let left = taken.clone(); let take: HostFunction = Rc::new(move |_| { c.borrow_mut().push(("paletteTake".into(), 0.0)); - Ok(taken.borrow_mut().pop_front().unwrap_or(Data::Null)) + Ok(left.borrow_mut().pop_front().unwrap_or(Data::Null)) + }); + let c = calls.clone(); + let pending: HostFunction = Rc::new(move |_| { + c.borrow_mut().push(("palettePending".into(), 0.0)); + Ok(Data::Bool(!taken.borrow().is_empty())) }); let draws = RefCell::new(VecDeque::from(draws)); let c = calls.clone(); @@ -433,6 +440,7 @@ fn palette_realm_with(events: Vec, taken: Vec, draws: Vec) -> ("paletteClose".into(), HostItem::Function(record("paletteClose", 0))), ("paletteEvent".into(), HostItem::Function(event)), ("paletteTake".into(), HostItem::Function(take)), + ("palettePending".into(), HostItem::Function(pending)), ("paletteDraw".into(), HostItem::Function(draw)), ]; r.define_script_ui(items).unwrap(); @@ -533,7 +541,27 @@ fn update_hands_a_waiting_click_to_the_palette_so_a_cancel_button_stops_a_loop() ) .unwrap(); assert_eq!(done, JsValue::String("1:true".into()), "the first update() runs the click's onClick"); - assert!(count(&calls, "paletteTake") >= 2, "update() takes events until none waits"); + assert_eq!(count(&calls, "paletteTake"), 1, "update() takes events while one waits"); + assert!(count(&calls, "palettePending") >= 2, "update() asks again after each event"); + let order = names(&calls); + let take = order.iter().position(|n| n == "paletteTake"); + let last_update = order.iter().rposition(|n| n == "paletteUpdate"); + assert!(take.zip(last_update).is_some_and(|(t, u)| u < t), "the host gets the controls before the event is taken"); +} + +#[test] +fn an_update_a_getter_calls_while_a_click_waits_leaves_the_click_to_the_update_taking_it() { + let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new()); + let done = r + .run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; var armed = false; \ + b.onClick = function () { clicks++; }; \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { reads++; p.update(); } return 'P'; }}); \ + p.show(); armed = true; p.update(); clicks + ':' + (reads > 0)", + ) + .unwrap(); + assert_eq!(done, JsValue::String("1:true".into()), "the getter's update() runs, and the click's onClick runs once"); + assert_eq!(count(&calls, "paletteTake"), 1); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 941a86437c..3623c6e560 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2993,7 +2993,9 @@ the same controls, handlers and limits: `update()` on the palette, or on a group or panel in it, first runs the handlers of the clicks, changes and closes that wait for the palettes of the run's engine, oldest first, so a Cancel button's `onClick` can stop a loop that calls `update()` (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). - Those events do not wait for runs of their own. In the app, an `update()` in the script's own code then + Those events do not wait for runs of their own. Each one is checked against the palette as the script and the + handlers before it left it, as an event's own run would be, so a click on a control that an earlier handler + disabled, hid or removed runs no handler. In the app, an `update()` in the script's own code then pauses the run so the app draws the palette as it is, at most once every 16 ms of the run's time (VectorCraft's own interval); an `update()` within the same 16 ms does not pause the run, and the app draws its changes at the next pause or when the run ends. An `update()` in a handler, in a callback of a built-in From 38937a1c0f6a835884c3920b493fa7abadf8cbb3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:21:19 -0800 Subject: [PATCH 11/34] Scripts: a palette text the full event line refuses stays in its field When 64 palette events already wait, a text change from an edit field is refused. The text had already been taken out of the field's draft, so the next frame showed the script's old text and what the person typed was lost. The refused text now goes back in its field, and the clicks and closes given after a refused change in the same frame are not put in line, so no handler runs without the change before it. --- crates/ui-egui/src/dialogs/script_window.rs | 5 +++ crates/ui-egui/src/script_palettes.rs | 31 +++++++++++++---- crates/ui-egui/src/tests/script_palettes.rs | 37 +++++++++++++++++++-- 3 files changed, 64 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 78e130bab2..69926adf4b 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -233,6 +233,11 @@ pub(crate) fn keep_refused_texts(w: &ScriptUiDialog, d: &mut Dialog, events: &mu refused } +/// Puts `text` back in the edit field `i` of the dialog's drafts `d`, as typed and not given yet. +pub(crate) fn keep_draft(d: &mut Dialog, i: usize, text: &str) { + d.fields.insert(draft_key(i), json!(text)); +} + /// The field that holds an edit field's text while it is typed. fn draft_key(i: usize) -> String { format!("text{i}") diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index ec2e8773dd..8ad4354dac 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -5,10 +5,11 @@ //! is going ([`crate::script_runs::poll`]); the palette stays usable while a run goes on, and its //! events wait for it. A palette does not take the keyboard focus when it opens or changes. An edit //! field's text is given when it loses the focus, at Enter in a one-line field, or before a click -//! or a close; a text the script would refuse stays in its field with the error in the status bar. +//! or a close; a text the script would refuse, or that the full line refuses, stays in its field +//! with the error in the status bar, and the click or close after it is not given. use serde_json::json; -use vectorcraft_engine::script::{ScriptPalette, UiEvent}; +use vectorcraft_engine::script::{ScriptPalette, UiEvent, UiValue}; use crate::VectorcraftApp; use crate::dialogs::script_window; @@ -49,8 +50,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { events.push(UiEvent::Close); } drafted(app, &p, &mut drafts, &mut events); + give(app, ctx, p.id, &mut drafts, events); keep_drafts(ctx, &p, drafts); - give(app, ctx, p.id, events); } } @@ -83,13 +84,31 @@ pub(crate) fn drafted(app: &mut VectorcraftApp, p: &ScriptPalette, drafts: &mut } } -/// Puts the events the person gave the palette `id` in line, or shows why one was refused. -pub(crate) fn give(app: &mut VectorcraftApp, ctx: &egui::Context, id: u64, events: Vec) { +/// Puts the events the person gave the palette `id` in line, or shows why one was refused. A +/// refused text goes back in its field (`drafts`), and once a change is refused, the clicks and +/// closes after it are not given, so no handler runs without the change before it. +pub(crate) fn give(app: &mut VectorcraftApp, ctx: &egui::Context, id: u64, drafts: &mut Dialog, events: Vec) { + let mut change_refused = false; for e in events { + if change_refused && matches!(e, UiEvent::Click(_) | UiEvent::Close) { + continue; + } + let change = match &e { + UiEvent::Change(i, value) => Some((*i, if let UiValue::Text(t) = value { Some(t.clone()) } else { None })), + _ => None, + }; match app.session.script_palette_event(id, e) { // The next frame starts its run. Ok(_) => ctx.request_repaint(), - Err(e) => app.status(e), + Err(error) => { + if let Some((i, text)) = change { + if let Some(text) = text { + script_window::keep_draft(drafts, i, &text); + } + change_refused = true; + } + app.status(error); + } } } } diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index b02fc382b2..f467004f6d 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -16,6 +16,11 @@ fn app() -> VectorcraftApp { app } +/// No text typed in a palette's fields. +fn drafts() -> Dialog { + Dialog::new(script_window::KIND, json!({})) +} + fn run_to_end(app: &mut VectorcraftApp) { for _ in 0..10_000 { if !app.session.script_running() { @@ -53,7 +58,10 @@ fn a_click_on_a_palette_asks_for_the_frame_that_starts_its_run() { frame(&ctx, |_| {}); } assert!(!frame(&ctx, |_| {}), "an idle frame asks for no other"); - assert!(frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])), "the click asks for the next frame"); + assert!( + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, &mut drafts(), vec![UiEvent::Click(1)])), + "the click asks for the next frame" + ); assert_eq!(app.session.script_palette_events_waiting(), 1); script_runs::poll(&mut app); run_to_end(&mut app); @@ -78,7 +86,7 @@ fn a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() { } assert!(app.session.script_dialog().is_some(), "the run waits at its confirm"); let ctx = egui::Context::default(); - frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])); + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, &mut drafts(), vec![UiEvent::Click(1)])); assert_eq!(app.session.script_palette_events_waiting(), 1); let mut asks = true; for _ in 0..5 { @@ -102,7 +110,7 @@ fn a_click_waiting_for_an_open_undo_group_asks_for_no_frames_and_runs_after_it() let id = app.session.script_palettes()[0].id; app.run("edit.undoGroup.begin", json!({})).unwrap(); let ctx = egui::Context::default(); - frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])); + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, &mut drafts(), vec![UiEvent::Click(1)])); assert_eq!(app.session.script_palette_events_waiting(), 1); let mut delay = std::time::Duration::ZERO; for _ in 0..5 { @@ -146,6 +154,29 @@ fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() { assert!(!drafts.fields.contains_key("text3")); } +#[test] +fn a_typed_text_the_full_line_refuses_stays_in_its_field() { + use vectorcraft_engine::script::palettes::MAX_WAITING; + let mut app = app(); + let source = format!( + "#targetengine full\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); go.onClick = function () {{ vc.log(t.text); }}; \ + for (var k = 0; k < {MAX_WAITING}; k++) {{ p.add('button', undefined, 'B' + k); }} p.show();" + ); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let id = app.session.script_palettes()[0].id; + let ctx = egui::Context::default(); + let fill: Vec = (3..3 + MAX_WAITING).map(UiEvent::Click).collect(); + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, &mut drafts(), fill.clone())); + assert_eq!(app.session.script_palette_events_waiting(), MAX_WAITING, "the line is full"); + let mut typed = drafts(); + let events = vec![UiEvent::Change(1, UiValue::Text("typed".into())), UiEvent::Click(2)]; + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, &mut typed, events.clone())); + assert_eq!(typed.fields.get("text1"), Some(&json!("typed")), "the refused text goes back in its field: {:?}", typed.fields); + assert_eq!(app.session.script_palette_events_waiting(), MAX_WAITING, "neither the text nor the click is kept"); +} + #[test] fn a_typed_text_the_script_refuses_keeps_the_palette_click_out_of_line() { let mut app = app(); From fab69d7f70878d20b58af5b23320a1affc9056d8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 12:10:36 -0800 Subject: [PATCH 12/34] Scripts: a palette's click or change keeps its control when a run changes the palette first The events the person gives a palette are kept with their control's id, and a list's change with the items they chose from, until the app puts them in line. A run that adds or removes controls before then no longer sends a click to the control now at the old index. --- crates/ui-egui/src/dialogs/script_window.rs | 4 ++-- crates/ui-egui/src/script_palettes.rs | 19 ++++++++++++------- crates/ui-egui/src/tests/script_palettes.rs | 18 ++++++++++++++++++ 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 3b7f6098c0..f97cf34bc7 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -259,7 +259,7 @@ pub(crate) fn keep_refused(w: &ScriptUiDialog, drafts: &mut BTreeMap Option { +pub(crate) fn queued(w: &ScriptUiDialog, event: &UiEvent) -> Option { let id = |i: usize| w.nodes.get(i).map(|n| n.id); Some(match event { UiEvent::Click(i) => Queued::Click(id(*i)?), @@ -274,7 +274,7 @@ fn queued(w: &ScriptUiDialog, event: &UiEvent) -> Option { /// The queued event `q` in the dialog `w`, with `control` the index its control has in `w` now. /// `None` when `w` no longer has the control, or for a list's change, when the list's items are no /// longer those the person chose from: other texts, or the same texts added again. -fn resolved(w: &ScriptUiDialog, q: Queued) -> Option { +pub(crate) fn resolved(w: &ScriptUiDialog, q: Queued) -> Option { match q { Queued::Click(id) => Some(UiEvent::Click(index_of(w, id)?)), Queued::Change(id, v, list) => { diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index 2e4047c09f..05c618c873 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -22,7 +22,7 @@ use vectorcraft_engine::script::{ScriptPalette, ScriptUiDialog, UiEvent, UiValue use crate::VectorcraftApp; use crate::dialogs::script_run::with_host; -use crate::dialogs::script_window; +use crate::dialogs::script_window::{self, Queued}; /// The dialog kind of a ScriptUI palette. pub const KIND: &str = "scriptPalette"; @@ -38,8 +38,10 @@ pub(crate) struct PaletteWindow { palette: ScriptPalette, /// The text typed in each edit field that the script has not had yet, by the field's id. drafts: BTreeMap, - /// The events the person gave since the app last took them. - given: Vec, + /// The events the person gave since the app last took them, each with its control by its id, + /// and a list's change with the items the person saw, so a run that changes the palette before + /// the app takes them leaves each with its own control. + given: Vec, open: bool, } @@ -72,7 +74,7 @@ impl PaletteWindow { /// Gives `event`, as the person does in the palette. #[cfg(test)] pub(crate) fn give(&mut self, event: UiEvent) { - self.given.push(event); + self.given.extend(script_window::queued(&self.palette.dialog, &event)); } } @@ -102,12 +104,12 @@ impl StackDialog for PaletteWindow { let shown = Dialog::new(heading).modeless().initial_focus(Initial::Keep).opened(Bind::bound(open)).show(ui, |ui, _| { events = script_window::controls(ui, &palette.dialog, drafts, true).events; }); - given.extend(events); + given.extend(events.iter().filter_map(|e| script_window::queued(&palette.dialog, e))); // The close box gives the script the close; the palette stays open until the script closes // it. if shown.output.closed.is_some() { self.open = true; - self.given.push(UiEvent::Close); + self.given.push(Queued::Close); } None } @@ -141,8 +143,11 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { taken }) .unwrap_or_default(); - for (id, mut drafts, mut events) in taken { + for (id, mut drafts, given) in taken { let Some(p) = shown.iter().find(|p| p.id == id) else { continue }; + // Each event goes to its control as the palette is now; one whose control is gone, or whose + // list's items changed since the person chose, is dropped. + let mut events: Vec = given.into_iter().filter_map(|q| script_window::resolved(&p.dialog, q)).collect(); drafted(app, &p.dialog, &mut drafts, &mut events); give(app, ctx, p, &mut drafts, events); with_host(app, |host, _| { diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 70462c2b51..b2e89992e0 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -164,6 +164,24 @@ fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() { assert_eq!(with_palette(&app, id, |w| w.typed(3).map(str::to_string)).unwrap(), None); } +#[test] +fn a_click_given_before_a_run_removes_a_control_before_it_reaches_its_button() { + let mut app = app(); + let source = "#targetengine moves\nvar p = new Window('palette'); var a = p.add('button', undefined, 'A'); \ + var b = p.add('button', undefined, 'B'); a.onClick = function () { vc.log('a'); }; \ + b.onClick = function () { vc.log('b'); }; p.show();"; + let id = shown(&mut app, source); + give(&app, id, UiEvent::Click(2)); + // A run removes A before the app takes the click, so B is now the palette's first control. + start(&mut app, "#targetengine moves\np.remove(a);"); + run_to_end(&mut app); + follow(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 1, "the click waits for its run"); + script_runs::poll(&mut app); + run_to_end(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["b"]), "the click reaches the button it was given to"); +} + #[test] fn a_typed_text_the_full_line_refuses_stays_in_its_field() { use vectorcraft_engine::script::palettes::MAX_WAITING; From ed0c7432ce0b0fa2806f661a7d703009ebce4c89 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 12:26:11 -0800 Subject: [PATCH 13/34] Scripts: no palette listener runs once an earlier one closed the palette A palette event checks before each listener that the palette still takes it, so a listener that closes the palette stops the listeners after it, on the control and on its containers. --- crates/js/src/scriptui.rs | 21 ++++++++++++--------- crates/js/src/scriptui_tests.rs | 14 ++++++++++++++ 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index fe3bd1fadb..970002c96b 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -939,8 +939,10 @@ fn event_stop(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult, event: ObjId, phase: f64) -> JsResult { +/// in the order they were added. A listener that an earlier one removed does not run, and none +/// runs once the palette of `taker` no longer takes the event. → whether it had any; `None` when +/// the palette stopped taking the event. +fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, (event, phase): (ObjId, f64), taker: Taker) -> JsResult> { let wanted = |i: &Interp| -> JsResult> { Ok(listeners_of(i, at)? .into_iter() @@ -950,7 +952,7 @@ fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, eve }; let first = wanted(i)?; if first.is_empty() { - return Ok(false); + return Ok(Some(false)); } let functions: Vec = first.iter().map(|(f, _)| f.clone()).collect(); i.rooted(&functions, |i| { @@ -960,9 +962,12 @@ fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, eve if !wanted(i)?.iter().any(|(g, d)| same(g, f) && d == c) { continue; } + if !takes(i, taker)? { + return Ok(None); + } i.call(f, &Value::Object(at), &[Value::Object(event)])?; } - Ok(true) + Ok(Some(true)) }) } @@ -1045,10 +1050,9 @@ fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: & if !containers_above(i, target)?.contains(p) { continue; } - if !takes(i, taker)? { + if run_listeners(i, *p, ty, Some(true), (event, 1.0), taker)?.is_none() { return Ok(None); } - run_listeners(i, *p, ty, Some(true), event, 1.0)?; if stopped(i)? { return Ok(Some(true)); } @@ -1068,16 +1072,15 @@ fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: & if !takes(i, taker)? { return Ok(None); } - let heard = run_listeners(i, target, ty, None, event, 2.0)?; + let Some(heard) = run_listeners(i, target, ty, None, (event, 2.0), taker)? else { return Ok(None) }; if bubbles && !stopped(i)? { for p in above { if !containers_above(i, target)?.contains(p) { continue; } - if !takes(i, taker)? { + if run_listeners(i, *p, ty, Some(false), (event, 3.0), taker)?.is_none() { return Ok(None); } - run_listeners(i, *p, ty, Some(false), event, 3.0)?; if stopped(i)? { break; } diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 428d0aaccc..def7bca945 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -711,6 +711,20 @@ fn a_palette_event_does_not_run_a_handler_once_a_getter_closed_the_palette() { assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); } +#[test] +fn a_palette_event_runs_no_more_listeners_once_one_closed_the_palette() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var later = 0; \ + b.addEventListener('click', function () { p.close(); }); b.addEventListener('click', function () { later++; }); \ + p.addEventListener('click', function () { later++; }); p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); + assert_eq!(r.run("later").unwrap(), JsValue::Number(0.0), "neither the next listener nor the palette's runs after the close"); +} + #[test] fn a_palette_list_change_does_not_run_on_change_once_an_item_s_text_getter_closed_the_palette() { let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); From 7737e97068a340fe5597baaa33113b47532722fe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 12:36:05 -0800 Subject: [PATCH 14/34] Scripts: a closed palette's visible is false `close()` and the close box set the palette's `visible` to false once `onClose` lets it close, as `hide()` does, so a script that checks `visible` stops updating a closed palette. --- crates/js/src/scriptui.rs | 6 ++++-- crates/js/src/scriptui_tests.rs | 2 ++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 970002c96b..9efffaa403 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -1428,8 +1428,9 @@ fn set_palettes(i: &mut Interp, f: impl FnOnce(&mut Vec)) { } } -/// Closes the palette `win` once its `onClose` allows it: the host no longer shows it and its -/// handlers no longer run. A `close()` while its `onClose` runs does nothing more. +/// Closes the palette `win` once its `onClose` allows it: the host no longer shows it, its +/// `visible` is false and its handlers no longer run. A `close()` while its `onClose` runs does +/// nothing more. fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { if slot(i, win, IN_CLOSE)?.truthy() { return Ok(()); @@ -1440,6 +1441,7 @@ fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { if let Value::Number(id) = slot(i, win, PALETTE_ID)? { set_slot(i, win, PALETTE_ID, Value::Undefined)?; set_slot(i, win, SHOWN, Value::Bool(false))?; + i.put(win, key("visible"), Value::Bool(false), true)?; set_palettes(i, |p| p.retain(|o| *o != win)); let f = host_fn(i, "paletteClose")?; i.call(&f, &Value::Undefined, &[Value::Number(id)])?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index def7bca945..ba8421c0f4 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -489,8 +489,10 @@ fn closing_a_palette_runs_on_close_which_can_keep_it_open() { .unwrap(); r.run("Window.__vcPaletteEvent();").unwrap(); assert!(!names(&calls).contains(&"paletteClose".to_string()), "the first onClose kept it open"); + assert_eq!(r.run("p.visible").unwrap(), JsValue::Bool(true), "a palette onClose kept open stays visible"); r.run("Window.__vcPaletteEvent(); Window.__vcPaletteEvent();").unwrap(); assert_eq!(r.run("[asked, clicks].join()").unwrap(), JsValue::String("2,0".into()), "a close inside onClose does not run it again"); + assert_eq!(r.run("p.visible").unwrap(), JsValue::Bool(false), "a closed palette is not visible"); assert_eq!(calls.borrow().iter().filter(|(n, _)| n == "paletteClose").count(), 1); assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); } From eb31682d720dbd82bfd7c1cb5fe906d02cc6e85b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 23:11:18 -0800 Subject: [PATCH 15/34] Scripts: reference-error tests name BridgeTalk now that Window is defined The tests on main checked the `vc` advice with `new Window('dialog')`, which throws a ReferenceError only where ScriptUI is missing. This branch defines `Window`, so those runs succeeded and the tests failed. They now use `BridgeTalk`, which stays undefined and is still in the list of other applications' objects. --- crates/engine/src/tests/script_run.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 9489921682..b9cdafb9c1 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -165,7 +165,7 @@ fn an_error_names_the_script_its_place_and_kind() { assert_eq!(e, "t.js: line 2, column 3: TypeError: no (thrown)"); let e = run(&mut s, "var = 1;").unwrap_err().to_string(); assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}"); - assert!(run(&mut s, "new Window('dialog');").unwrap_err().to_string().contains("`vc`")); + assert!(run(&mut s, "new BridgeTalk();").unwrap_err().to_string().contains("`vc`")); // The application's members need no `app.`, so naming one alone is not an error. assert_eq!(run(&mut s, "activeDocument;").unwrap()["ok"], true); assert!(run(&mut s, "#targetengine 9x\n1").unwrap_err().to_string().contains("#targetengine needs a name of letters, digits and _")); @@ -182,7 +182,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { ("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"), ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), ("throw 'invalid array length';", "thrown", "invalid array length", "script"), - ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), + ("throw 'ReferenceError: BridgeTalk is not defined';", "thrown", "ReferenceError: BridgeTalk is not defined", "script"), ("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"), ("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"), ("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"), @@ -206,7 +206,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { assert_eq!(error, Some(json!(format!("t.js:{line}:{column}: {message}"))), "{source}"); } // The app's own reference error names the `vc` object; the same text a script threw does not. - run(&mut s, "new Window('dialog');").unwrap_err(); + run(&mut s, "new BridgeTalk();").unwrap_err(); assert!(s.script_report().unwrap()["message"].as_str().unwrap().contains("`vc`")); assert_eq!(s.script_report().unwrap()["messageOrigin"], "built-in"); // An error in code `eval` compiled keeps where its message came from. From 2666d077129235b965ad11620f54db55b88fefd0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 19:51:43 -0800 Subject: [PATCH 16/34] Scripts: a list made with items counts each one in its revision Main's new_items builds a list's items in one step without counting them in the list's revision, so a palette event for a list made with two items carried a revision the list no longer had and was refused. Count each item as add does. Also apply rustfmt to two lines from the merge. --- crates/js/src/scriptui.rs | 12 +++++++++++- crates/ui-egui/src/dialogs/script_window.rs | 4 +--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 45ce3b4496..1f15cfb006 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -885,6 +885,9 @@ fn new_items(i: &mut Interp, o: ObjId, texts: &[Value]) -> JsResult { let kept = list(i, &items, false)?; i.temp_roots.push(Value::Object(kept)); set_items(i, o, kept)?; + // Each item counts as one change of the list's items ([`REVISION`]), as `add` counts it. + let revision = number_slot(i, o, REVISION)? + items.len() as f64; + set_slot(i, o, REVISION, Value::Number(revision))?; let copy = list(i, &items, true)?; set_open(i, o, "items", Value::Object(copy))?; Ok(items.len()) @@ -1204,7 +1207,14 @@ fn event_stop(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult, (event, phase, cutoff): (ObjId, f64, f64), taker: Taker) -> JsResult> { +fn run_listeners( + i: &mut Interp, + at: ObjId, + ty: &str, + capture: Option, + (event, phase, cutoff): (ObjId, f64, f64), + taker: Taker, +) -> JsResult> { let wanted = |i: &Interp| -> JsResult> { Ok(listeners_of(i, at)? .into_iter() diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index ae84b4138f..074b2a5567 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -333,9 +333,7 @@ impl StackDialog for ScriptWindow { let dialog = Dialog::new(heading).buttons(buttons).initial_focus(initial).opened(Bind::bound(open)); // The body can run twice in a pass (measure, then paint), so it only reports what the // person did; the dialog applies the last run's report after the container. - let shown = dialog.show(ui, |ui, _| { - controls(ui, window, drafts, waiting) - }); + let shown = dialog.show(ui, |ui, _| controls(ui, window, drafts, waiting)); let pass = shown.inner.unwrap_or_default(); if pass.layer.is_some() { self.layer = pass.layer; From 91f413e9bbf2aff84c6b145839dbfc51fd650b0d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:56:12 -0800 Subject: [PATCH 17/34] Scripts: palette events keep the file scope they were given in Queued palette events keep the file access scope of the pass that gave them, and update() runs only the events whose scope the running script already has. update() on a removed container throws an error the script can catch. The palette dialog returns its events from the Dialog body, and the palette and script window tests run their frames through testing::part_frame. --- crates/engine/src/file_access.rs | 17 +++ crates/engine/src/script/palettes.rs | 28 +++-- crates/engine/src/tests/script_palettes.rs | 114 ++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 3 +- crates/js/src/scriptui.rs | 15 ++- crates/ui-egui/src/script_palettes.rs | 62 +++++++--- crates/ui-egui/src/tests/script_palettes.rs | 93 +++++++++++++- crates/ui-egui/src/tests/script_window.rs | 9 +- docs/mcp.md | 6 +- 9 files changed, 312 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index d5641d9606..e4b3a2df02 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -262,6 +262,23 @@ impl ScopeHandle { Self(Some(scope), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get)) } + /// Whether this scope allows everything the calling thread's scope allows: its roots are none or + /// the same roots, and its script gate is none or the same gate. + pub(crate) fn covers_current(&self) -> bool { + let here = Self::capture(); + let gate = match (&self.1, &here.1) { + (None, _) => true, + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + (Some(_), None) => false, + }; + let roots = match (self.roots(), here.roots()) { + (None, _) => true, + (Some(a), Some(b)) => Arc::ptr_eq(&a, &b), + (Some(_), None) => false, + }; + gate && roots + } + /// Run `f` in the captured scope. pub fn run(self, f: impl FnOnce() -> T) -> T { let Self(scope, gate, exempt) = self; diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 6298ec23d9..104ac1e1d8 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -75,6 +75,9 @@ pub(crate) struct Queued { /// Once its run starts, the SHA-256 the file grants of the palette's script are kept for, which /// the run takes as its own ([`super::files::Setup::own`]). pub(crate) grants: Option, + /// The file access scope of the request that gave the event, which its run keeps, narrowed to + /// the scope in force when the run starts ([`crate::file_access::ScopeHandle::within_current`]). + pub(crate) scope: crate::file_access::ScopeHandle, } /// The palettes of a session, and the events that wait for a run. @@ -173,15 +176,17 @@ impl Palettes { _ => None, }; let element = control_of(&mut event).and_then(|c| p.dialog.nodes.get(*c)).map(|n| n.id); + let scope = crate::file_access::ScopeHandle::capture(); if let Some(slot) = self.waiting.iter_mut().find(|q| q.palette == id && same_place(q, &event, element)) { slot.event = event; slot.list = list; + slot.scope = scope; return Ok(Waiting::Merged); } if self.waiting.len() >= MAX_WAITING { return Err(format!("{MAX_WAITING} script palette events already wait; this one was not kept")); } - self.waiting.push_back(Queued { palette: id, event, element, list, grants: None }); + self.waiting.push_back(Queued { palette: id, event, element, list, grants: None, scope }); Ok(Waiting::Added) } @@ -199,11 +204,12 @@ impl Palettes { } /// As [`Palettes::next`], for the palettes of the engine `engine` only: the events of other - /// engines' palettes keep their places in line. + /// engines' palettes keep their places in line. Events whose file access scopes do not cover + /// the run's scope wait for runs of their own ([`Queued::scope`]). Eligible events run oldest + /// first, preserving the order within each scope. fn next_of(&mut self, engine: &str) -> Option<(ScriptPalette, Queued)> { loop { - let list = &self.list; - let at = self.waiting.iter().position(|q| list.iter().any(|p| p.id == q.palette && p.engine == engine))?; + let at = self.oldest_for(engine)?; let q = self.waiting.remove(at)?; if let Some(taken) = self.checked(q) { return Some(taken); @@ -244,7 +250,13 @@ impl Palettes { /// Whether an event waits for a palette of the engine `engine`, which [`Palettes::take_for`] /// would then check and take. pub(crate) fn waits_for(&self, engine: &str) -> bool { - self.waiting.iter().any(|q| self.list.iter().any(|p| p.id == q.palette && p.engine == engine)) + self.oldest_for(engine).is_some() + } + + /// The place of the oldest event for a palette of `engine`, when a palette's `update()` in a + /// run of that engine may take it ([`Palettes::next_of`]). + fn oldest_for(&self, engine: &str) -> Option { + self.waiting.iter().position(|q| q.scope.covers_current() && self.list.iter().any(|p| p.id == q.palette && p.engine == engine)) } } @@ -257,7 +269,7 @@ fn engine_line(name: &str) -> String { /// The source of a palette's handler run: its engine, and the call that hands the event to the /// palette, which takes it from the run's host. fn handler_source(engine: &str) -> String { - format!("{}\nWindow.__vcPaletteEvent();\n", engine_line(engine)) + format!("{}\nthis[{:?}]();\n", engine_line(engine), vectorcraft_js::scriptui::PALETTE_EVENT_GLOBAL) } /// The event `event` (`click`, `change` or `close`) for `dialog`, from `script.palette.event`'s @@ -406,8 +418,10 @@ impl Session { module: false, actions: Vec::new(), }; + // The run takes the scope of the request that gave the event, within the scope in force now. + let scope = queued.scope.clone().within_current(); self.script_palettes.starting = Some(queued); - let r = self.script_start(request); + let r = scope.run(|| self.script_start(request)); self.script_palettes.starting = None; Some(r) } diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 54de688f93..539dcb87fb 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -250,6 +250,81 @@ fn a_handler_keeps_the_file_grants_of_the_script_that_showed_the_palette() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn update_takes_eligible_events_past_deferred_events_in_scope_order() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine eligible\nvar p = new Window('palette'); var stopped = false; \ + var a = p.add('button', undefined, 'A'); var b = p.add('button', undefined, 'B'); \ + var c = p.add('button', undefined, 'C'); var cancel = p.add('button', undefined, 'Cancel'); \ + a.onClick = function () { vc.log('a'); }; b.onClick = function () { vc.log('b'); }; \ + c.onClick = function () { vc.log('c'); }; cancel.onClick = function () { stopped = true; vc.log('cancel'); }; p.show();", + ); + let id = only_palette(&s); + let roots = crate::file_access::AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + for control in 1..=4 { + let queued = if control % 2 == 1 { + crate::file_access::confine(Some(&roots), || s.script_palette_event(id, UiEvent::Click(control))) + } else { + crate::file_access::unconfined(|| s.script_palette_event(id, UiEvent::Click(control))) + }; + assert_eq!(queued, Ok(Waiting::Added)); + } + let report = crate::file_access::unconfined(|| run_in_app(&mut s, "#targetengine eligible\nwhile (!stopped) p.update(); vc.log('stopped');")); + assert_eq!(report["log"], json!(["b", "cancel", "stopped"])); + assert_eq!(s.script_palette_events_waiting(), 2); + for expected in ["a", "c"] { + crate::file_access::unconfined(|| { + assert!(s.script_palette_start().unwrap().is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([expected])); + }); + } + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn a_handler_keeps_the_file_access_scope_of_the_request_that_gave_its_event() { + let base = std::env::temp_dir().join(format!("vc-script-palette-scope-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("other")).unwrap(); + let base = std::fs::canonicalize(&base).unwrap(); + std::fs::write(base.join("main/data.txt"), "hello").unwrap(); + let main = base.join("main/main.jsx"); + let path = serde_json::to_string(&base.join("main/data.txt").to_string_lossy()).unwrap(); + std::fs::write( + &main, + format!( + "#targetengine scope\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Read'); var stop = false; \ + b.onClick = function () {{ stop = true; vc.log(new File({path}).exists); }}; p.show();" + ), + ) + .unwrap(); + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); + pump(&mut s).expect("the run ended").unwrap(); + let id = only_palette(&s); + let roots = crate::file_access::AutomationRoots::new(&[&base.join("other")], &[]).unwrap().unwrap(); + // A confined request gives the click; the frame that starts its run later is not confined. + assert_eq!(crate::file_access::confine(Some(&roots), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); + // An update() in a later unconfined run of the engine leaves the confined click waiting. + let r = crate::file_access::unconfined(|| run_in_app(&mut s, "#targetengine scope\np.update(); vc.log(stop);")); + assert_eq!(r["log"], json!([false]), "{r}"); + assert_eq!(s.script_palette_events_waiting(), 1); + crate::file_access::unconfined(|| { + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("the handler ended").unwrap()["log"], json!([false]), "the handler reads inside the roots only"); + // A click the person gives, as the desktop app's pass gives it, goes to an update() at once. + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + let r = run_in_app(&mut s, "#targetengine scope\nstop = false; for (var k = 0; k < 1000 && !stop; k++) p.update(); vc.log(stop);"); + assert_eq!(r["log"].as_array().and_then(|l| l.last()), Some(&json!(true)), "the handler ran in the update() loop: {r}"); + }); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn a_failed_run_in_the_engine_still_changes_what_the_palette_shows() { let mut s = one_doc(); @@ -496,6 +571,45 @@ fn close_fires_on_close_and_frees_the_window() { assert!(s.script_palettes().is_empty(), "close() freed the palette"); } +#[test] +fn update_on_a_removed_group_throws_an_error_the_script_catches_and_keeps_the_engine() { + let mut s = one_doc(); + let r = run( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); var g = p.add('group'); p.show(); p.remove(g); \ + try { g.update(); } catch (e) { vc.log(e.message); } vc.log('after');", + ) + .unwrap(); + assert_eq!(r["log"], json!(["update: the control was removed from its dialog", "after"]), "{r}"); + assert_eq!(s.script_palettes().len(), 1, "the engine and its palette stay"); +} + +#[test] +fn a_palette_still_takes_events_after_the_script_replaces_window() { + let mut s = one_doc(); + run(&mut s, &format!("{TOOLS} Window = function () {{}};")).unwrap(); + let id = only_palette(&s); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": "Go"})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"])); + run(&mut s, "#targetengine tools\nWindow = 5;").unwrap(); + let closed = s.execute("script.palette.event", &json!({"palette": id, "event": "close"})).unwrap(); + assert!(closed["ok"].as_bool().unwrap_or(false), "{closed}"); + assert!(s.script_palettes().is_empty(), "the close box reached the palette"); +} + +#[test] +fn closing_a_palette_whose_visible_is_read_only_still_closes_it() { + let mut s = one_doc(); + let r = run( + &mut s, + &format!( + "{TOOLS} Object.defineProperty(p, 'visible', {{value: true, writable: false}}); try {{ p.close(); }} catch (e) {{ vc.log(e.name); }}" + ), + ) + .unwrap(); + assert!(s.script_palettes().is_empty(), "the host closed the palette: {r}"); +} + #[test] fn dropping_the_engine_closes_its_palettes() { let mut s = one_doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ddde9d70a9..143e054e8a 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -46,8 +46,9 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// change anything outside it. The document model (`app`, its classes and the enumerations) acts on /// the open documents; `Document.saveAs` and `close` throw "not available yet". const INSIDE: &[(&str, &str)] = &[ - ("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"), + ("", "$ %vcPaletteEvent File Folder UnitValue Window alert confirm localize prompt toSource"), ("Window.", "__vcPaletteEvent alert confirm length prompt prototype"), + ("%vcPaletteEvent.", "length"), ("Window.prototype.", "add addEventListener center close constructor findElement hide remove removeEventListener show update"), ("Object.prototype.", "reflect toSource"), ("UnitValue.", "baseUnit baseUnit= length prototype"), diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 1f15cfb006..131db628db 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -94,6 +94,10 @@ use crate::interp::{Abrupt, ErrorType, Interp, JsResult, Pause}; use crate::scriptui_resource::{self, Fault, Res, Spec}; use crate::value::{Value, index_key}; +/// The global property, not an identifier, that the run of a palette's handler calls as +/// `this[PALETTE_EVENT_GLOBAL]()` to take its event ([`palette_event`]). +pub const PALETTE_EVENT_GLOBAL: &str = "%vcPaletteEvent"; + /// 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. @@ -1654,7 +1658,7 @@ fn control_update(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult if !is_container(&kind) { return Err(i.type_error("update: this is not a ScriptUI window or container")); } - let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a container without its window".into())) }; + let win = window_of(i, o, "update")?; let palette = matches!(slot(i, win, KIND)?, Value::String(s) if s.to_rust_string() == "palette"); update_window(i, win, palette, own)?; Ok(Value::Undefined) @@ -1742,10 +1746,11 @@ fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { if let Value::Number(id) = slot(i, win, PALETTE_ID)? { set_slot(i, win, PALETTE_ID, Value::Undefined)?; set_slot(i, win, SHOWN, Value::Bool(false))?; - i.put(win, key("visible"), Value::Bool(false), true)?; set_palettes(i, |p| p.retain(|o| *o != win)); let f = host_fn(i, "paletteClose")?; i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + // The host has closed it; a `visible` the script made read-only stays as it is. + i.put(win, key("visible"), Value::Bool(false), false)?; } Ok(()) } @@ -2551,8 +2556,12 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul constructor(i, "Window", window, window_proto)?; let event = native(i, "__vcPaletteEvent", palette_event, 0, NativeKind::Plain, false)?; i.define(window, key("__vcPaletteEvent"), Prop::Data { value: Value::Object(event), flags: 0 })?; - // `Window.alert`, `Window.confirm` and `Window.prompt` are the host's global functions. + // The run of a palette's handler calls the global one through `this`, under a name that is + // not an identifier: a script can neither replace nor delete it nor declare the name, so + // the palettes still take events after a script assigns to `Window`. let global = i.global; + i.define(global, key(PALETTE_EVENT_GLOBAL), Prop::Data { value: Value::Object(event), flags: 0 })?; + // `Window.alert`, `Window.confirm` and `Window.prompt` are the host's global functions. for name in ["alert", "confirm", "prompt"] { if let Some(Prop::Data { value, .. }) = i.get_own_property(global, &key(name))? && i.is_callable(&value) diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index 251afb4e78..2548b08b45 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -18,6 +18,7 @@ use craft::ui::contract::{Bind, ShowContainer as _}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; use craft::ui::runtime::focus::Initial; use egui::Ui; +use vectorcraft_engine::file_access::ScopeHandle; use vectorcraft_engine::script::{ScriptPalette, ScriptUiDialog, UiEvent, UiValue}; use crate::VectorcraftApp; @@ -41,7 +42,7 @@ pub(crate) struct PaletteWindow { /// The events the person gave since the app last took them, each with its control by its id, /// and a list's change with the items the person saw, so a run that changes the palette before /// the app takes them leaves each with its own control. - given: Vec, + given: Vec<(ScopeHandle, Vec)>, open: bool, } @@ -74,7 +75,14 @@ impl PaletteWindow { /// Gives `event`, as the person does in the palette. #[cfg(test)] pub(crate) fn give(&mut self, event: UiEvent) { - self.given.extend(script_window::queued(&self.palette.dialog, &event)); + self.record(std::slice::from_ref(&event)); + } + + fn record(&mut self, events: &[UiEvent]) { + let events: Vec = events.iter().filter_map(|e| script_window::queued(&self.palette.dialog, e)).collect(); + if !events.is_empty() { + self.given.push((ScopeHandle::capture_now(), events)); + } } } @@ -99,7 +107,7 @@ impl StackDialog for PaletteWindow { fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let heading = script_window::heading(&self.palette.dialog); - let PaletteWindow { palette, drafts, given, open } = self; + let PaletteWindow { palette, drafts, open, .. } = self; let (palette, drafts_now) = (&*palette, &*drafts); // The body can run twice in a pass (measure, then paint), so the last run's report is // applied after the container. @@ -115,14 +123,14 @@ impl StackDialog for PaletteWindow { None => drafts.remove(&id), }; } - let events = pass.events; - given.extend(events.iter().filter_map(|e| script_window::queued(&palette.dialog, e))); + let mut events = pass.events; // The close box gives the script the close; the palette stays open until the script closes // it. if shown.output.closed.is_some() { self.open = true; - self.given.push(Queued::Close); + events.push(UiEvent::Close); } + self.record(&events); None } } @@ -132,6 +140,10 @@ impl StackDialog for PaletteWindow { /// each palette in line. pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let shown: Vec = app.session.script_palettes().iter().filter(|p| p.visible).cloned().collect(); + // A new palette waits while the run waits at a modal dialog, a file dialog or a growth prompt, + // which stays the top dialog and takes its answers. + let s = &app.session; + let modal = s.script_window().is_some() || s.script_dialog().is_some() || s.script_picker().is_some() || s.script_waiting(); let taken = with_host(app, |host, ctx| { let ids: Vec = shown.iter().map(|p| palette_id(p.id)).collect(); for d in host.open_dialogs() { @@ -147,9 +159,10 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { w.sync(p.clone()); taken.push((p.id, std::mem::take(&mut w.drafts), std::mem::take(&mut w.given))); } - None => { + None if !modal => { host.open(PaletteWindow::new(p.clone())); } + None => {} } } taken @@ -159,9 +172,14 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(p) = shown.iter().find(|p| p.id == id) else { continue }; // Each event goes to its control as the palette is now; one whose control is gone, or whose // list's items changed since the person chose, is dropped. - let mut events: Vec = given.into_iter().filter_map(|q| script_window::resolved(&p.dialog, q)).collect(); - drafted(app, &p.dialog, &mut drafts, &mut events); - give(app, ctx, p, &mut drafts, events); + let mut change_refused = false; + for (scope, given) in given { + scope.run(|| { + let mut events: Vec = given.into_iter().filter_map(|q| script_window::resolved(&p.dialog, q)).collect(); + drafted(app, &p.dialog, &mut drafts, &mut events); + give(app, ctx, p, &mut drafts, events, &mut change_refused); + }); + } with_host(app, |host, _| { if let Some(w) = host.get_mut_by_id::(palette_id(id)) { w.drafts = drafts; @@ -188,10 +206,16 @@ fn drafted(app: &mut VectorcraftApp, w: &ScriptUiDialog, drafts: &mut BTreeMap, events: Vec) { - let mut change_refused = false; +fn give( + app: &mut VectorcraftApp, + ctx: &egui::Context, + p: &ScriptPalette, + drafts: &mut BTreeMap, + events: Vec, + change_refused: &mut bool, +) { for e in events { - if change_refused && matches!(e, UiEvent::Click(_) | UiEvent::Close) { + if *change_refused && matches!(e, UiEvent::Click(_) | UiEvent::Close) { continue; } let change = match &e { @@ -200,13 +224,21 @@ fn give(app: &mut VectorcraftApp, ctx: &egui::Context, p: &ScriptPalette, drafts }; match app.session.script_palette_event(p.id, e) { // The next frame starts its run. - Ok(_) => ctx.request_repaint(), + Ok(_) => { + if let Some((i, Some(text))) = &change + && let Some(n) = p.dialog.nodes.get(*i) + && drafts.get(&n.id) == Some(text) + { + drafts.remove(&n.id); + } + ctx.request_repaint(); + } Err(error) => { if let Some((i, text)) = change { if let Some((n, text)) = p.dialog.nodes.get(i).zip(text) { drafts.insert(n.id, text); } - change_refused = true; + *change_refused = true; } app.status(error); } diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index b2e89992e0..76ed72bf68 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -46,8 +46,7 @@ fn follow(app: &mut VectorcraftApp) { fn frame_delay(app: &mut VectorcraftApp, mut f: impl FnMut(&mut VectorcraftApp, &egui::Context)) -> std::time::Duration { let ctx = app.ui_ctx.clone().unwrap(); let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); - let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| f(app, ui.ctx())); - out.textures_delta.clear(); + let out = crate::testing::part_frame(app, &ctx, egui::RawInput { screen_rect, ..Default::default() }, |app, ui| f(app, ui.ctx())); out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) } @@ -91,6 +90,27 @@ fn a_script_dialog_opens_while_a_palette_is_open() { assert!(is_open::(&app)); } +#[test] +fn a_palette_shown_before_a_modal_dialog_does_not_open_above_it() { + let mut app = app(); + start( + &mut app, + "#targetengine tools\nvar p = new Window('palette', 'Tools'); p.add('button', undefined, 'Go'); p.show(); \ + var d = new Window('dialog', 'Ask'); d.add('button', undefined, 'OK'); vc.log(d.show());", + ); + for _ in 0..10_000 { + if app.session.script_window().is_some() { + break; + } + script_runs::poll(&mut app); + } + assert!(app.session.script_window().is_some(), "the run waits at its dialog"); + script_runs::poll(&mut app); + follow(&mut app); + assert!(crate::dialogs::script_window::is_top(&app), "the modal dialog stays on top and takes its answers"); + assert!(!is_open::(&app), "the palette waits for the modal dialog to close"); +} + #[test] fn a_click_on_a_palette_asks_for_the_frame_that_starts_its_run() { let mut app = app(); @@ -105,6 +125,75 @@ fn a_click_on_a_palette_asks_for_the_frame_that_starts_its_run() { assert_eq!(app.session.script_palette_events_waiting(), 0); } +#[test] +fn recorded_palette_events_keep_their_scopes_across_the_engine_handoff() { + use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; + + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + for recorded_confined in [false, true] { + let mut app = app(); + let id = shown(&mut app, TOOLS); + if recorded_confined { + confine(Some(&roots), || give(&app, id, UiEvent::Click(1))); + unconfined(|| follow(&mut app)); + } else { + unconfined(|| give(&app, id, UiEvent::Click(1))); + confine(Some(&roots), || follow(&mut app)); + } + unconfined(|| { + start(&mut app, "#targetengine tools\np.update(); vc.log('after');"); + run_to_end(&mut app); + }); + if recorded_confined { + assert_eq!(app.session.script_report().unwrap()["log"], json!(["after"])); + assert_eq!(app.session.script_palette_events_waiting(), 1); + unconfined(|| { + script_runs::poll(&mut app); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked"])); + } else { + assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked", "after"])); + } + assert_eq!(app.session.script_palette_events_waiting(), 0); + } +} + +#[test] +fn a_recorded_text_change_is_not_given_again_in_a_later_clicks_scope() { + use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; + + let mut app = app(); + let id = shown( + &mut app, + "#targetengine texts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); t.onChange = function () { vc.log('changed'); }; \ + go.onClick = function () { vc.log('clicked'); }; p.show();", + ); + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + confine(Some(&roots), || { + with_palette(&app, id, |w| { + w.type_text(1, "typed"); + w.give(UiEvent::Change(1, UiValue::Text("typed".into()))); + }) + .unwrap(); + }); + unconfined(|| { + give(&app, id, UiEvent::Click(2)); + follow(&mut app); + start(&mut app, "#targetengine texts\np.update(); vc.log(t.text);"); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked", "a"])); + assert_eq!(app.session.script_palette_events_waiting(), 1); + unconfined(|| { + script_runs::poll(&mut app); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["changed"])); + assert_eq!(app.session.script_palettes()[0].dialog.nodes[1].text, "typed"); +} + #[test] fn a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() { let mut app = app(); diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 7c51e909ea..8fb119da7f 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -532,8 +532,7 @@ fn a_run_waiting_at_its_dialog_asks_for_no_frames() { let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); let mut delay = std::time::Duration::ZERO; for _ in 0..5 { - let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| app.tick(ui.ctx())); - out.textures_delta.clear(); + let out = crate::testing::part_frame(&mut app, &ctx, egui::RawInput { screen_rect, ..Default::default() }, |app, ui| app.tick(ui.ctx())); delay = out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay); if delay == std::time::Duration::MAX { break; @@ -552,8 +551,7 @@ fn a_control_request_while_a_run_waits_at_its_dialog_asks_for_the_next_frame() { let ctx = app.ui_ctx.clone().unwrap(); let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); let drain = |app: &mut VectorcraftApp| { - let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| app.run_control(ui.ctx())); - out.textures_delta.clear(); + let out = crate::testing::part_frame(app, &ctx, egui::RawInput { screen_rect, ..Default::default() }, |app, ui| app.run_control(ui.ctx())); out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) }; // A new context asks for a frame or two of its own first. @@ -581,8 +579,7 @@ fn a_pass_that_gives_the_dialog_s_queued_event_asks_for_the_next_frame() { let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); // One pass of the frame's pump, which gives the run the dialog's next queued event. let pass = |app: &mut VectorcraftApp| { - let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |_| script_window::pump(app)); - out.textures_delta.clear(); + let out = crate::testing::part_frame(app, &ctx, egui::RawInput { screen_rect, ..Default::default() }, |app, _| script_window::pump(app)); out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) }; let mut settled = false; diff --git a/docs/mcp.md b/docs/mcp.md index 431c5022cc..2f8adeb092 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3859,7 +3859,11 @@ the same controls, handlers and limits: `update()` on the palette, or on a group or panel in it, first runs the handlers of the clicks, changes and closes that wait for the palettes of the run's engine, oldest first, so a Cancel button's `onClick` can stop a loop that calls `update()` (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). - Those events do not wait for runs of their own. Each one is checked against the palette as the script and the + `update()` takes eligible events oldest first. Events whose recorded file access scopes do not cover the run's + scope stay queued for runs of their own, while later eligible events for the same engine can run. Events within + one scope keep their order. A desktop event keeps the scope in force when the widget records it, even if the app + hands it to the engine under different automation roots. Each deferred event runs in its recorded scope within + the scope in force when its run starts. Each one is checked against the palette as the script and the handlers before it left it, as an event's own run would be, so a click on a control that an earlier handler disabled, hid or removed runs no handler. In the app, an `update()` in the script's own code then pauses the run so the app draws the palette as it is, at most once every 16 ms of the run's time From 48b59a3ccc9d9c072d5deff398bf88000345ab93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 21:28:02 -0800 Subject: [PATCH 18/34] Scripts: palette events and typed texts keep their own file access scope A waiting palette event merges with a newer one only when both have the same file access scope, and a click or close merges only after its palette's last waiting change. A text typed in a field keeps the scope of each pass that edited it and goes to the script under what both that scope and the committing pass allow; a click or close that commits it takes those limits too. Passes recorded before the app takes them stay separate. Scope coverage checks root containment instead of comparing the same roots object, and the progress line describes when update() runs a waiting event. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/file_access.rs | 30 +- crates/engine/src/script/palettes.rs | 23 +- crates/engine/src/tests/script_palettes.rs | 129 +++++++ crates/ui-egui/src/script_palettes.rs | 175 +++++++-- crates/ui-egui/src/tests/script_palettes.rs | 386 ++++++++++++++++++++ docs/mcp.md | 9 +- docs/target-app-parity.md | 2 +- 8 files changed, 707 insertions(+), 49 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index c8925f0621..f4aeea23d9 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Script Palette Event", [], None, - "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; while it waits, another click on the same control, change of it or close of the same palette takes its place with the newer value, and a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", + "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", always, palette_event ), diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index e4b3a2df02..528b387a97 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -148,6 +148,13 @@ impl AutomationRoots { Arc::new(Self { read: both(&self.read, &other.read), write: both(&self.write, &other.write) }) } + /// Whether these roots grant everything `other` grants: each root of `other` lies inside one of + /// these roots of the same kind. + pub(crate) fn contains(&self, other: &Self) -> bool { + let within = |mine: &[Root], theirs: &[Root]| theirs.iter().all(|o| mine.iter().any(|r| inside(&o.resolved, &r.resolved))); + within(&self.read, &other.read) && within(&self.write, &other.write) + } + /// The roots for people: `read A, B; write C` (`none` for a kind without any). pub fn describe(&self) -> String { let list = |roots: &[Root]| { @@ -262,23 +269,34 @@ impl ScopeHandle { Self(Some(scope), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get)) } - /// Whether this scope allows everything the calling thread's scope allows: its roots are none or - /// the same roots, and its script gate is none or the same gate. + /// Whether this scope allows everything the calling thread's scope allows ([`ScopeHandle::covers`]). pub(crate) fn covers_current(&self) -> bool { - let here = Self::capture(); - let gate = match (&self.1, &here.1) { + self.covers(&Self::capture()) + } + + /// Whether this scope allows everything `other` allows: its roots are none, or each root of + /// `other` lies inside one of its roots of the same kind, and its script gate is none or the + /// same gate. + fn covers(&self, other: &Self) -> bool { + let gate = match (&self.1, &other.1) { (None, _) => true, (Some(a), Some(b)) => Arc::ptr_eq(a, b), (Some(_), None) => false, }; - let roots = match (self.roots(), here.roots()) { + let roots = match (self.roots(), other.roots()) { (None, _) => true, - (Some(a), Some(b)) => Arc::ptr_eq(&a, &b), + (Some(a), Some(b)) => Arc::ptr_eq(&a, &b) || a.contains(&b), (Some(_), None) => false, }; gate && roots } + /// Whether this scope and `other` allow the same: each covers the other, and reads are exempt + /// from the gate in both or in neither. + pub fn same(&self, other: &Self) -> bool { + self.2 == other.2 && self.covers(other) && other.covers(self) + } + /// Run `f` in the captured scope. pub fn run(self, f: impl FnOnce() -> T) -> T { let Self(scope, gate, exempt) = self; diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 104ac1e1d8..e02e4727f1 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -6,11 +6,12 @@ //! without `#targetengine`, or with `main`, `new Window("palette")` throws. `show()` returns at once. //! Each click, change or close the person gives a palette waits here, and then runs as a run of its //! own in the palette's engine, which takes the mutation lease like any other run: one event at a -//! time, oldest first, each starting only once no run is going. While an event waits, another click -//! on the same control, another change of it or another close of the same palette takes its place -//! in line, with the newer value, instead of waiting as well. A palette's `update()` in a run of the -//! palette's engine takes the events that wait for that engine's palettes and runs their handlers in -//! that run instead ([`Palettes::take_for`]). +//! time, oldest first, each starting only once no run is going. A new click, change or close replaces +//! the most recent waiting event of the same kind for the same control or palette only when that +//! event has the same file access scope. Otherwise the new event waits at the end of the line. A click or +//! close replaces an event only after its palette's last waiting change. A palette's `update()` in +//! a run of the palette's engine takes the events that wait for that engine's palettes and runs their +//! handlers in that run instead ([`Palettes::take_for`]). //! //! A palette closes when its script calls `close()` or the person closes it, unless `onClose` //! returns `false`; when its engine is dropped or ends with an internal error; and with the session. @@ -177,10 +178,18 @@ impl Palettes { }; let element = control_of(&mut event).and_then(|c| p.dialog.nodes.get(*c)).map(|n| n.id); let scope = crate::file_access::ScopeHandle::capture(); - if let Some(slot) = self.waiting.iter_mut().find(|q| q.palette == id && same_place(q, &event, element)) { + // Only the most recent event for the same place can merge, in the same file access scope. + // A click or close merges only after its palette's last waiting change. + let closing = matches!(event, UiEvent::Click(_) | UiEvent::Close); + let after = if closing { + self.waiting.iter().rposition(|q| q.palette == id && matches!(q.event, UiEvent::Change(..))).map_or(0, |at| at + 1) + } else { + 0 + }; + let at = self.waiting.iter_mut().skip(after).rev().find(|q| q.palette == id && same_place(q, &event, element)); + if let Some(slot) = at.filter(|q| q.scope.same(&scope)) { slot.event = event; slot.list = list; - slot.scope = scope; return Ok(Waiting::Merged); } if self.waiting.len() >= MAX_WAITING { diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 539dcb87fb..2618cd9083 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -283,6 +283,135 @@ fn update_takes_eligible_events_past_deferred_events_in_scope_order() { assert_eq!(s.script_palette_events_waiting(), 0); } +#[test] +fn a_change_does_not_take_the_place_of_a_waiting_change_given_in_another_scope() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine merge\nvar p = new Window('palette'); var t = p.add('edittext', undefined, ''); \ + var b = p.add('button', undefined, 'B'); t.onChange = function () { vc.log('change ' + t.text); }; \ + b.onClick = function () { vc.log('click'); }; p.show();", + ); + let id = only_palette(&s); + let roots = crate::file_access::AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + let change = |text: &str| UiEvent::Change(1, crate::script::UiValue::Text(text.into())); + assert_eq!(crate::file_access::confine(Some(&roots), || s.script_palette_event(id, change("x"))), Ok(Waiting::Added)); + crate::file_access::unconfined(|| { + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, change("y")), Ok(Waiting::Added), "the confined change keeps its own place"); + }); + let report = crate::file_access::unconfined(|| run_in_app(&mut s, "#targetengine merge\np.update();")); + assert_eq!(report["log"], json!(["click", "change y"]), "the click stays before the later change of its scope"); + assert_eq!(s.script_palette_events_waiting(), 1); +} + +#[test] +fn a_change_does_not_merge_past_a_waiting_change_given_in_another_scope() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine merge\nvar p = new Window('palette'); var t = p.add('edittext', undefined, ''); \ + t.onChange = function () { vc.log('change ' + t.text); }; p.show();", + ); + let id = only_palette(&s); + let roots = crate::file_access::AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + let change = |text: &str| UiEvent::Change(1, crate::script::UiValue::Text(text.into())); + assert_eq!(crate::file_access::confine(Some(&roots), || s.script_palette_event(id, change("x"))), Ok(Waiting::Added)); + assert_eq!(crate::file_access::unconfined(|| s.script_palette_event(id, change("y"))), Ok(Waiting::Added)); + assert_eq!(crate::file_access::confine(Some(&roots), || s.script_palette_event(id, change("z"))), Ok(Waiting::Added)); + assert_eq!(s.script_palette_events_waiting(), 3); + let mut logs = Vec::new(); + crate::file_access::unconfined(|| { + while let Some(started) = s.script_palette_start() { + started.unwrap(); + logs.push(pump(&mut s).unwrap().unwrap()["log"].clone()); + } + }); + assert_eq!(logs, [json!(["change x"]), json!(["change y"]), json!(["change z"])]); + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn a_click_does_not_take_a_place_ahead_of_a_change_that_waits_after_it() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine ahead\nvar p = new Window('palette'); var t = p.add('edittext', undefined, ''); \ + var b = p.add('button', undefined, 'B'); t.onChange = function () { vc.log('change ' + t.text); }; \ + b.onClick = function () { vc.log('click ' + t.text); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Change(1, crate::script::UiValue::Text("y".into()))), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added), "the click waits after the change"); + let report = run_in_app(&mut s, "#targetengine ahead\np.update();"); + assert_eq!(report["log"], json!(["click ", "change y", "click y"])); +} + +#[test] +fn repeated_clicks_and_closes_merge_after_the_last_change_of_their_palette() { + use crate::file_access::{AutomationRoots, confine, unconfined}; + + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + for closing in [UiEvent::Click(1), UiEvent::Close] { + for confined_change in [false, true] { + let mut s = one_doc(); + run_in_app(&mut s, &format!("{TOOLS} p.onClose = function () {{ vc.log('close'); return false; }};")); + let id = only_palette(&s); + unconfined(|| assert_eq!(s.script_palette_event(id, closing.clone()), Ok(Waiting::Added))); + let change = UiEvent::Change(2, crate::script::UiValue::Text("typed".into())); + let queued = if confined_change { + confine(Some(&roots), || s.script_palette_event(id, change)) + } else { + unconfined(|| s.script_palette_event(id, change)) + }; + assert_eq!(queued, Ok(Waiting::Added)); + unconfined(|| { + assert_eq!(s.script_palette_event(id, closing.clone()), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, closing.clone()), Ok(Waiting::Merged)); + }); + assert_eq!(s.script_palette_events_waiting(), 3); + let mut logs = Vec::new(); + unconfined(|| { + while let Some(started) = s.script_palette_start() { + started.unwrap(); + logs.push(pump(&mut s).unwrap().unwrap()["log"].clone()); + } + }); + let expected = if matches!(closing, UiEvent::Close) { + [json!(["close"]), json!(["change typed"]), json!(["close"])] + } else { + [json!(["click 1"]), json!(["change typed"]), json!(["click 2"])] + }; + assert_eq!(logs, expected); + } + } +} + +#[test] +fn update_takes_events_whose_roots_grant_all_the_run_s_roots_grant() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine contain\nvar p = new Window('palette'); var b = p.add('button', undefined, 'B'); \ + b.onClick = function () { vc.log('clicked'); }; p.show();", + ); + let id = only_palette(&s); + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap(); + let inner = base.join(format!("vc-script-palette-contain-{}", std::process::id())); + std::fs::create_dir_all(&inner).unwrap(); + let wide = crate::file_access::AutomationRoots::new(&[&base], &[]).unwrap().unwrap(); + let same = crate::file_access::AutomationRoots::new(&[&base], &[]).unwrap().unwrap(); + let narrow = crate::file_access::AutomationRoots::new(&[&inner], &[]).unwrap().unwrap(); + for (run_roots, what) in [(same, "the same roots made again"), (narrow, "roots inside the event's roots")] { + assert_eq!(crate::file_access::confine(Some(&wide), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); + let report = crate::file_access::confine(Some(&run_roots), || run_in_app(&mut s, "#targetengine contain\np.update(); vc.log('after');")); + assert_eq!(report["log"], json!(["clicked", "after"]), "{what}: {report}"); + assert_eq!(s.script_palette_events_waiting(), 0, "{what}"); + } + let _ = std::fs::remove_dir(inner); +} + #[test] fn a_handler_keeps_the_file_access_scope_of_the_request_that_gave_its_event() { let base = std::env::temp_dir().join(format!("vc-script-palette-scope-{}", std::process::id())); diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index 2548b08b45..e5f71acac2 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -39,16 +39,18 @@ pub(crate) struct PaletteWindow { palette: ScriptPalette, /// The text typed in each edit field that the script has not had yet, by the field's id. drafts: BTreeMap, + /// Each draft's typing scope, narrowed by every pass that edits the text. + draft_scopes: BTreeMap, /// The events the person gave since the app last took them, each with its control by its id, /// and a list's change with the items the person saw, so a run that changes the palette before /// the app takes them leaves each with its own control. - given: Vec<(ScopeHandle, Vec)>, + given: Vec<(ScopeHandle, ScopeHandle, Vec)>, open: bool, } impl PaletteWindow { fn new(palette: ScriptPalette) -> Self { - PaletteWindow { palette, drafts: BTreeMap::new(), given: Vec::new(), open: true } + PaletteWindow { palette, drafts: BTreeMap::new(), draft_scopes: BTreeMap::new(), given: Vec::new(), open: true } } /// The palette as the session has it now. A typed text whose field the palette no longer has is @@ -68,21 +70,95 @@ impl PaletteWindow { #[cfg(test)] pub(crate) fn type_text(&mut self, i: usize, text: &str) { if let Some(n) = self.palette.dialog.nodes.get(i) { - self.drafts.insert(n.id, text.to_string()); + self.take_pass(vec![(n.id, Some(text.to_string()))], Vec::new()); } } + /// Gives the text typed in edit field `i` as `text`, as the field does at Enter or when it loses + /// the focus. + #[cfg(test)] + pub(crate) fn commit_text(&mut self, i: usize, text: &str) { + if let Some(n) = self.palette.dialog.nodes.get(i) { + self.take_pass(vec![(n.id, None)], vec![UiEvent::Change(i, UiValue::Text(text.to_string()))]); + } + } + + /// Takes one pass's typed texts (by field index) and events, as the palette's body reports them. + #[cfg(test)] + pub(crate) fn pass(&mut self, drafts: &[(usize, Option<&str>)], events: Vec) { + let drafts = drafts.iter().filter_map(|(i, t)| self.palette.dialog.nodes.get(*i).map(|n| (n.id, t.map(str::to_string)))).collect(); + self.take_pass(drafts, events); + } + /// Gives `event`, as the person does in the palette. #[cfg(test)] pub(crate) fn give(&mut self, event: UiEvent) { - self.record(std::slice::from_ref(&event)); + self.record(std::slice::from_ref(&event), &BTreeMap::new()); } - fn record(&mut self, events: &[UiEvent]) { - let events: Vec = events.iter().filter_map(|e| script_window::queued(&self.palette.dialog, e)).collect(); - if !events.is_empty() { - self.given.push((ScopeHandle::capture_now(), events)); + /// Takes what the person did in one pass: the typed texts (`None` for a field whose text was + /// given or dropped) and the events. A typed text keeps the scope of each pass that edited it, + /// narrowed to what all of them allow, and a text the field gives goes in line in that scope. + fn take_pass(&mut self, drafts: Vec<(u64, Option)>, events: Vec) { + let mut committed = BTreeMap::new(); + for (id, draft) in drafts { + match draft { + Some(text) => { + // A pass that leaves the text as it was leaves its scope as it was too. + let edited = self.drafts.get(&id) != Some(&text); + let scope = match self.draft_scopes.remove(&id) { + Some(typed) if edited => typed.within_current(), + Some(typed) => typed, + None => ScopeHandle::capture_now(), + }; + self.draft_scopes.insert(id, scope); + self.drafts.insert(id, text); + } + None => { + if let Some(typed) = self.draft_scopes.remove(&id) { + committed.insert(id, typed); + } + self.drafts.remove(&id); + } + } } + self.record(&events, &committed); + } + + /// Puts `events` in line in the scope of the calling thread, except that a field's change takes + /// the scope its text was typed in (`committed`), narrowed to this one. Every click or close + /// in the pass also takes what all of those text scopes allow. + fn record(&mut self, events: &[UiEvent], committed: &BTreeMap) { + let here = ScopeHandle::capture_now(); + let given: Vec = events + .iter() + .filter_map(|e| match e { + UiEvent::Change(i, UiValue::Text(_)) => self.palette.dialog.nodes.get(*i).and_then(|n| committed.get(&n.id)), + _ => None, + }) + .map(|t| t.clone().within_current()) + .collect(); + let mut events: Vec<_> = events.iter().collect(); + events.sort_by_key(|e| matches!(e, UiEvent::Click(_) | UiEvent::Close)); + let mut batches: Vec<(ScopeHandle, Vec)> = Vec::new(); + for e in events { + let Some(q) = script_window::queued(&self.palette.dialog, e) else { continue }; + let typed = match e { + UiEvent::Change(i, UiValue::Text(_)) => self.palette.dialog.nodes.get(*i).and_then(|n| committed.get(&n.id)), + _ => None, + }; + let mut scope = typed.map_or_else(|| here.clone(), |t| t.clone().within_current()); + if matches!(e, UiEvent::Click(_) | UiEvent::Close) { + for t in &given { + scope = t.clone().run(|| scope.within_current()); + } + } + match batches.last_mut() { + Some((last, list)) if last.same(&scope) => list.push(q), + _ => batches.push((scope, vec![q])), + } + } + self.given.extend(batches.into_iter().map(|(scope, events)| (here.clone(), scope, events))); } } @@ -117,12 +193,6 @@ impl StackDialog for PaletteWindow { .opened(Bind::bound(open)) .show(ui, |ui, _| script_window::controls(ui, &palette.dialog, drafts_now, true)); let pass = shown.inner.unwrap_or_default(); - for (id, draft) in pass.drafts { - match draft { - Some(text) => drafts.insert(id, text), - None => drafts.remove(&id), - }; - } let mut events = pass.events; // The close box gives the script the close; the palette stays open until the script closes // it. @@ -130,7 +200,7 @@ impl StackDialog for PaletteWindow { self.open = true; events.push(UiEvent::Close); } - self.record(&events); + self.take_pass(pass.drafts.into_iter().collect(), events); None } } @@ -157,7 +227,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { match host.get_mut_by_id::(palette_id(p.id)) { Some(w) => { w.sync(p.clone()); - taken.push((p.id, std::mem::take(&mut w.drafts), std::mem::take(&mut w.given))); + taken.push((p.id, std::mem::take(&mut w.drafts), std::mem::take(&mut w.draft_scopes), std::mem::take(&mut w.given))); } None if !modal => { host.open(PaletteWindow::new(p.clone())); @@ -168,39 +238,80 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { taken }) .unwrap_or_default(); - for (id, mut drafts, given) in taken { + for (id, mut drafts, mut draft_scopes, given) in taken { let Some(p) = shown.iter().find(|p| p.id == id) else { continue }; // Each event goes to its control as the palette is now; one whose control is gone, or whose // list's items changed since the person chose, is dropped. let mut change_refused = false; - for (scope, given) in given { - scope.run(|| { - let mut events: Vec = given.into_iter().filter_map(|q| script_window::resolved(&p.dialog, q)).collect(); - drafted(app, &p.dialog, &mut drafts, &mut events); - give(app, ctx, p, &mut drafts, events, &mut change_refused); - }); + for (pass_scope, scope, given) in given { + let mut events: Vec = given.into_iter().filter_map(|q| script_window::resolved(&p.dialog, q)).collect(); + for (event_scope, event) in drafted(app, &p.dialog, &mut drafts, &mut events, &scope, &pass_scope, &draft_scopes) { + event_scope.run(|| give(app, ctx, p, &mut drafts, vec![event], &mut change_refused)); + } + // A text that went back in its field without a scope of its own takes this one. + for field in drafts.keys() { + draft_scopes.entry(*field).or_insert_with(|| scope.clone()); + } } + draft_scopes.retain(|field, _| drafts.contains_key(field)); with_host(app, |host, _| { if let Some(w) = host.get_mut_by_id::(palette_id(id)) { w.drafts = drafts; + w.draft_scopes = draft_scopes; } }); } } -/// Puts the text still typed in the fields of palette `w` (`drafts`) before a click or a close in -/// `events`. A text the script would refuse stays in its field with its error in the status bar, -/// and a click or a close waits for the person to fix it. -fn drafted(app: &mut VectorcraftApp, w: &ScriptUiDialog, drafts: &mut BTreeMap, events: &mut Vec) { +/// Commits drafts in dialog order, each under its typing and committing scopes. Every draft is +/// validated before any is removed. A refused draft keeps the click or close out of line. +fn drafted( + app: &mut VectorcraftApp, + w: &ScriptUiDialog, + drafts: &mut BTreeMap, + events: &mut Vec, + scope: &ScopeHandle, + pass_scope: &ScopeHandle, + draft_scopes: &BTreeMap, +) -> Vec<(ScopeHandle, UiEvent)> { if let Some(e) = script_window::keep_refused(w, drafts, events) { app.status(e); } - if events.iter().any(|e| matches!(e, UiEvent::Click(_) | UiEvent::Close)) - && let Err(e) = script_window::commit_texts(w, drafts, events) - { - events.retain(|e| !matches!(e, UiEvent::Click(_) | UiEvent::Close)); - app.status(e); + let closing = |e: &UiEvent| matches!(e, UiEvent::Click(_) | UiEvent::Close); + let mut changes = Vec::new(); + if events.iter().any(closing) { + changes.extend(events.iter().filter(|e| !closing(e)).cloned()); + let existing = changes.len(); + match script_window::commit_texts(w, drafts, &mut changes) { + Ok(()) => { + drop(changes.drain(..existing)); + } + Err(e) => { + changes.clear(); + events.retain(|e| !closing(e)); + app.status(e); + } + } } + let mut closing_scope = scope.clone(); + let changes: Vec<_> = changes + .into_iter() + .map(|event| { + let typed = match &event { + UiEvent::Change(i, _) => w.nodes.get(*i).and_then(|n| draft_scopes.get(&n.id)), + _ => None, + }; + let narrowed = pass_scope.clone().run(|| typed.map_or_else(|| pass_scope.clone(), |t| t.clone().within_current())); + closing_scope = narrowed.clone().run(|| closing_scope.clone().within_current()); + (narrowed, event) + }) + .collect(); + events.sort_by_key(closing); + let at = events.iter().position(closing).unwrap_or(events.len()); + let mut given: Vec<_> = events.drain(..at).map(|e| (scope.clone(), e)).collect(); + given.extend(changes); + given.extend(events.drain(..).map(|e| (closing_scope.clone(), e))); + given } /// Puts the events the person gave the palette `p` in line, or shows why one was refused. A diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 76ed72bf68..f45977156c 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -194,6 +194,392 @@ fn a_recorded_text_change_is_not_given_again_in_a_later_clicks_scope() { assert_eq!(app.session.script_palettes()[0].dialog.nodes[1].text, "typed"); } +#[test] +fn a_typed_text_goes_to_the_script_in_the_scope_it_was_typed_in() { + use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; + + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); t.onChange = function () { vc.log('changed'); }; \ + go.onClick = function () { vc.log('clicked'); }; p.show();", + ); + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(1, "typed")).unwrap()); + unconfined(|| { + give(&app, id, UiEvent::Click(2)); + follow(&mut app); + start(&mut app, "#targetengine drafts\np.update(); vc.log(t.text);"); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["a"]), "the text and the click that gave it wait in the confined scope"); + assert_eq!(app.session.script_palette_events_waiting(), 2); + for expected in ["changed", "clicked"] { + unconfined(|| { + script_runs::poll(&mut app); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!([expected])); + } + assert_eq!(app.session.script_palettes()[0].dialog.nodes[1].text, "typed"); +} + +#[test] +fn a_click_or_close_narrows_the_scope_of_the_draft_it_commits() { + use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; + + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + for closing in [UiEvent::Click(2), UiEvent::Close] { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); t.onChange = function () { vc.log('changed'); }; \ + go.onClick = function () { vc.log('clicked ' + t.text); }; \ + p.onClose = function () { vc.log('closed ' + t.text); return false; }; p.show();", + ); + unconfined(|| with_palette(&app, id, |w| w.type_text(1, "typed")).unwrap()); + confine(Some(&roots), || give(&app, id, closing.clone())); + unconfined(|| { + follow(&mut app); + start(&mut app, "#targetengine drafts\np.update(); vc.log(t.text);"); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["a"]), "the committed draft waits in the confined scope"); + assert_eq!(app.session.script_palette_events_waiting(), 2); + let last = if matches!(closing, UiEvent::Close) { "closed typed" } else { "clicked typed" }; + for expected in ["changed", last] { + unconfined(|| { + script_runs::poll(&mut app); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!([expected])); + } + assert_eq!(app.session.script_palette_events_waiting(), 0); + } +} + +#[test] +fn a_text_typed_in_two_scopes_goes_to_the_script_in_what_both_allow() { + use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; + + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + t.onChange = function () { vc.log('changed'); }; p.show();", + ); + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + unconfined(|| with_palette(&app, id, |w| w.type_text(1, "ty")).unwrap()); + confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(1, "typed")).unwrap()); + unconfined(|| { + with_palette(&app, id, |w| w.commit_text(1, "typed")).unwrap(); + follow(&mut app); + start(&mut app, "#targetengine drafts\np.update(); vc.log(t.text);"); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["a"]), "the text waits in the confined scope"); + assert_eq!(app.session.script_palette_events_waiting(), 1); +} + +#[test] +fn a_click_in_the_pass_that_gives_a_text_runs_after_the_text() { + use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; + + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); t.onChange = function () { vc.log('changed'); }; \ + go.onClick = function () { vc.log('clicked ' + t.text); }; p.show();", + ); + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(1, "typed")).unwrap()); + unconfined(|| { + with_palette(&app, id, |w| w.pass(&[(1, None)], vec![UiEvent::Change(1, UiValue::Text("typed".into())), UiEvent::Click(2)])).unwrap(); + follow(&mut app); + start(&mut app, "#targetengine drafts\np.update(); vc.log(t.text);"); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["a"]), "the click waits with the text it follows"); + assert_eq!(app.session.script_palette_events_waiting(), 2); +} + +#[test] +fn a_click_reported_before_a_text_commit_waits_in_the_texts_scope() { + use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; + + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var go = p.add('button', undefined, 'Go'); \ + var t = p.add('edittext', undefined, 'a'); t.onChange = function () { vc.log('changed'); }; \ + go.onClick = function () { vc.log('clicked ' + t.text); }; p.show();", + ); + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(2, "typed")).unwrap()); + unconfined(|| { + with_palette(&app, id, |w| w.pass(&[(2, None)], vec![UiEvent::Click(1), UiEvent::Change(2, UiValue::Text("typed".into()))])).unwrap(); + follow(&mut app); + start(&mut app, "#targetengine drafts\np.update(); vc.log(t.text);"); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["a"]), "both events wait in the text's confined scope"); + assert_eq!(app.session.script_palette_events_waiting(), 2); + for expected in ["changed", "clicked typed"] { + unconfined(|| { + script_runs::poll(&mut app); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!([expected])); + } + assert_eq!(app.session.script_palette_events_waiting(), 0); +} + +#[test] +fn a_pass_orders_changes_before_a_click_before_splitting_scopes() { + use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; + + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var a = p.add('edittext', undefined, 'a'); \ + var b = p.add('edittext', undefined, 'b'); var go = p.add('button', undefined, 'Go'); \ + a.onChange = function () { vc.log('first ' + a.text); }; b.onChange = function () { vc.log('second ' + b.text); }; \ + go.onClick = function () { vc.log(a.text + ' ' + b.text); }; p.show();", + ); + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + unconfined(|| with_palette(&app, id, |w| w.type_text(1, "first")).unwrap()); + confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(2, "second")).unwrap()); + unconfined(|| { + with_palette(&app, id, |w| { + w.pass( + &[(1, None), (2, None)], + vec![UiEvent::Click(3), UiEvent::Change(1, UiValue::Text("first".into())), UiEvent::Change(2, UiValue::Text("second".into()))], + ); + }) + .unwrap(); + follow(&mut app); + }); + assert_eq!(app.session.script_palette_events_waiting(), 3); + for expected in ["first first", "second second", "first second"] { + unconfined(|| { + script_runs::poll(&mut app); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!([expected])); + } + assert_eq!(app.session.script_palette_events_waiting(), 0); +} + +#[test] +fn a_focus_loss_and_click_or_close_keep_another_drafts_scope_independent() { + use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; + + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + for closing in [UiEvent::Click(3), UiEvent::Close] { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var a = p.add('edittext', undefined, 'a'); \ + var b = p.add('edittext', undefined, 'b'); var go = p.add('button', undefined, 'Go'); \ + a.onChange = function () { vc.log('first ' + a.text); }; b.onChange = function () { vc.log('second ' + b.text); }; \ + go.onClick = function () { vc.log(a.text + ' ' + b.text); }; \ + p.onClose = function () { vc.log(a.text + ' ' + b.text); return false; }; p.show();", + ); + confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(1, "first")).unwrap()); + unconfined(|| { + with_palette(&app, id, |w| { + w.type_text(2, "second"); + w.pass(&[(1, None)], vec![UiEvent::Change(1, UiValue::Text("first".into())), closing]); + }) + .unwrap(); + follow(&mut app); + start(&mut app, "#targetengine drafts\np.update(); vc.log(a.text + ' ' + b.text);"); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["second second", "a second"])); + assert_eq!(app.session.script_palette_events_waiting(), 2); + for expected in ["first first", "first second"] { + unconfined(|| { + script_runs::poll(&mut app); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!([expected])); + } + assert_eq!(app.session.script_palette_events_waiting(), 0); + } +} + +#[test] +fn buffered_passes_keep_a_click_or_close_before_a_later_text_commit() { + use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; + + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + for confined in [false, true] { + for closing in [UiEvent::Click(2), UiEvent::Close] { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); t.onChange = function () { vc.log('changed ' + t.text); }; \ + go.onClick = function () { vc.log('clicked ' + t.text); }; \ + p.onClose = function () { vc.log('closed ' + t.text); return false; }; p.show();", + ); + let first = if matches!(closing, UiEvent::Close) { "closed a" } else { "clicked a" }; + let record = || { + with_palette(&app, id, |w| { + w.pass(&[], vec![closing]); + w.type_text(1, "typed"); + w.commit_text(1, "typed"); + }) + .unwrap(); + }; + if confined { + confine(Some(&roots), record); + } else { + unconfined(record); + } + unconfined(|| follow(&mut app)); + assert_eq!(app.session.script_palette_events_waiting(), 2); + for expected in [first, "changed typed"] { + unconfined(|| { + script_runs::poll(&mut app); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!([expected])); + } + assert_eq!(app.session.script_palette_events_waiting(), 0); + } + } +} + +#[test] +fn a_click_or_close_commits_drafts_in_dialog_order_across_scopes() { + use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; + + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + for closing in [UiEvent::Click(3), UiEvent::Close] { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var a = p.add('edittext', undefined, 'a'); \ + var b = p.add('edittext', undefined, 'b'); var go = p.add('button', undefined, 'Go'); \ + a.onChange = function () { vc.log('first ' + a.text); }; b.onChange = function () { vc.log('second ' + a.text); }; \ + go.onClick = function () { vc.log(a.text + ' ' + b.text); }; \ + p.onClose = function () { vc.log(a.text + ' ' + b.text); return false; }; p.show();", + ); + let long = "x".repeat(16 * 1024 + 1); + confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(2, &long)).unwrap()); + unconfined(|| { + with_palette(&app, id, |w| w.type_text(1, "first")).unwrap(); + give(&app, id, closing.clone()); + follow(&mut app); + }); + assert_eq!(app.session.script_palette_events_waiting(), 0, "every draft is validated before any is queued"); + assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).unwrap(), Some("first".into())); + assert_eq!(with_palette(&app, id, |w| w.typed(2).map(str::to_string)).unwrap(), Some(long)); + confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(2, "second")).unwrap()); + unconfined(|| { + give(&app, id, closing); + follow(&mut app); + }); + assert_eq!(app.session.script_palette_events_waiting(), 3); + for expected in ["first first", "second first", "first second"] { + unconfined(|| { + script_runs::poll(&mut app); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!([expected])); + } + assert_eq!(app.session.script_palette_events_waiting(), 0); + } +} + +#[test] +fn a_click_that_flushes_two_scopes_keeps_each_texts_scope() { + use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; + + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var a = p.add('edittext', undefined, 'a'); \ + var b = p.add('edittext', undefined, 'b'); var go = p.add('button', undefined, 'Go'); \ + a.onChange = function () { vc.log('wide ' + a.text); }; b.onChange = function () { vc.log('narrow ' + b.text); }; \ + go.onClick = function () { vc.log(a.text + ' ' + b.text); }; p.show();", + ); + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + unconfined(|| with_palette(&app, id, |w| w.type_text(1, "first")).unwrap()); + confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(2, "second")).unwrap()); + unconfined(|| { + give(&app, id, UiEvent::Click(3)); + follow(&mut app); + start(&mut app, "#targetengine drafts\np.update(); vc.log(a.text + ' ' + b.text);"); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["wide first", "first b"]), "the wide change runs in the wide scope"); + assert_eq!(app.session.script_palette_events_waiting(), 2, "the narrow change and the click still wait"); + for expected in ["narrow second", "first second"] { + unconfined(|| { + script_runs::poll(&mut app); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!([expected])); + } + assert_eq!(app.session.script_palette_events_waiting(), 0); +} + +#[test] +fn a_pass_that_leaves_a_typed_text_as_it_was_keeps_its_scope() { + use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; + + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + t.onChange = function () { vc.log('changed'); }; p.show();", + ); + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + unconfined(|| with_palette(&app, id, |w| w.type_text(1, "typed")).unwrap()); + confine(Some(&roots), || with_palette(&app, id, |w| w.pass(&[(1, Some("typed"))], Vec::new())).unwrap()); + unconfined(|| { + with_palette(&app, id, |w| w.commit_text(1, "typed")).unwrap(); + follow(&mut app); + start(&mut app, "#targetengine drafts\np.update(); vc.log(t.text);"); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["changed", "typed"])); + assert_eq!(app.session.script_palette_events_waiting(), 0); +} + +#[test] +fn a_text_given_at_enter_goes_to_the_script_in_the_scope_it_was_typed_in() { + use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; + + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + t.onChange = function () { vc.log('changed'); }; p.show();", + ); + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(1, "typed")).unwrap()); + unconfined(|| { + with_palette(&app, id, |w| w.commit_text(1, "typed")).unwrap(); + follow(&mut app); + start(&mut app, "#targetengine drafts\np.update(); vc.log(t.text);"); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["a"]), "the text waits in its confined scope"); + assert_eq!(app.session.script_palette_events_waiting(), 1); + unconfined(|| { + script_runs::poll(&mut app); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["changed"])); +} + #[test] fn a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 2f8adeb092..b05820412e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3878,8 +3878,13 @@ the same controls, handlers and limits: - Each click, change or close the person gives a palette runs its handler as a run of its own in the palette's engine, with its own report and, when it changes a document, its own Run Script undo step. While another run goes on, the event waits and runs after it; events run one at a time, oldest first. While an event waits, a - newer click on the same control, change of the same control or close of the same palette takes its place, - with the newer value. A waiting click or change, and a text typed in a field, stay with their control when a + newer click on the same control, change of the same control or close of the same palette replaces the most + recent waiting event of that kind for that control or palette only when it has the same file access scope. + Otherwise the new event waits at the end of the line (`merged: false`). A click or close takes its place only if no + change of its palette waits after it; otherwise it waits as a new event (`merged: false`). A text typed in + a field goes to the script under what both its typing scope and the scope that commits it allow. A click + or close waits under what its scope and all the texts it commits allow. A text edited in several scopes + goes under what all of them allow. A waiting click or change, and a text typed in a field, stay with their control when a run adds controls before it. A waiting event whose control is gone, or that its control can no longer take because a handler disabled or hid it, is dropped. A list's change ends its run with an error when a script added or removed the list's items after the person chose, even if the list again diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 878b2b4579..bfa0036a86 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1180,7 +1180,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`). - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person and runs the controls' `onClick`, `onChanging` and `onChange` handlers. The window's own callbacks are `onShow`, which runs when `show()` starts, and `onClose`, which runs before the dialog closes and keeps it open when it returns false. `show()` returns the result of `close(result)`, or 1 for the default button and 2 for the cancel button when the button has no `onClick` or click listener and no handler closed the dialog with another result. Controls also take `notify`, size objects a script can set one side of, lists' `find` and `remove`, and `addEventListener` for clicks and changes, which the dialog also takes for `show`; `Window.alert`, `Window.confirm` and `Window.prompt` open the script dialogs; a run over MCP or the command line takes the clicks and changes from a `window` answer. `new Window` and `add` also build a window or a control and the controls inside it from a resource specification (https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/). Other control types throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`. - - Scripts: ScriptUI's `new Window("palette")` in a script with `#targetengine` shows a palette that stays open beside the documents after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going; a newer event for the same control takes a waiting one's place. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes, so a Cancel button can stop a loop, and in the script's own code in the app pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. A palette closes with `close()`, its close box, or the end of its engine or the session; at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.rs`. + - Scripts: ScriptUI's `new Window("palette")` in a script with `#targetengine` shows a palette that stays open beside the documents after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going; a newer event for the same control, given under the same file access scope, takes a waiting one's place. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes whose file access scopes cover the run's scope, so a Cancel button can stop a loop; an event given under narrower roots or another script gate waits for a run of its own instead. `update()` in the script's own code in the app also pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. A palette closes with `close()`, its close box, or the end of its engine or the session; at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.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`). From 7b3690163eea7a2010edd9ac057ab5ad861fb14f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 03:31:54 -0800 Subject: [PATCH 19/34] Scripts: palette events report their own run, and dialogs keep typed texts on a failed handoff - script.palette.event with nobody to ask answers with the report of the run that handled the given event, also when it took the place of an earlier waiting event or a run of its engine took it with update(); an event dropped without a run is an error, and a later event that cannot start leaves the given event's result. An open drag in a document other than the active one is refused before the event waits, and the app's palette start check uses the same rule. - A palette event's handler and the refresh after a run take no waiting event through update(), so a later event does not run inside them. The refresh after a named run spends at most the unbroken-run allowance. - A click whose button a getter removed during the event runs no handler. - A window answer that could not reach the script lists the dialog with the answer "error" instead of "stop". - In a ScriptUI dialog, Escape, ui.dialog.cancel and a click keep the typed texts when the run does not take the event, and a refused event asks for the next frame so the queued events after it go on. - Quitting while only palettes are open asks whether to stop the run. --- crates/engine/src/cmd/scripts.rs | 6 +- crates/engine/src/script/dialogs.rs | 14 ++++- crates/engine/src/script/palettes.rs | 66 +++++++++++++++++---- crates/engine/src/tests/script_palettes.rs | 13 ++++ crates/js/src/realm.rs | 13 +++- crates/js/src/scriptui.rs | 27 ++++++++- crates/js/src/scriptui_tests.rs | 18 ++++++ crates/ui-egui/src/dialogs/script_run.rs | 3 +- crates/ui-egui/src/dialogs/script_window.rs | 26 ++++++-- docs/mcp.md | 16 +++-- 10 files changed, 169 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index f4aeea23d9..a55af85287 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Script Palette Event", [], None, - "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", + "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error", always, palette_event ), @@ -305,8 +305,8 @@ fn palette_event(s: &mut Session, p: &Value) -> Result { let Some(palette) = s.script_palettes().iter().find(|q| q.id == id) else { return Err(bad(C, format!("there is no script palette {id}"))) }; let event = script::palettes::parse_event(&palette.dialog, event, p.get("control"), p.get("value")).map_err(|e| bad(C, e))?; // With nobody to ask, the event runs now or not at all: it is not kept for after an open undo - // group, which a run cannot start in. - if !s.script_frames && s.undo_group_open() { + // group or a drag in another document, which a run cannot start in. + if !s.script_frames && s.palette_run_blocked() { return Err(EngineError::Other(script::OPEN_EDIT.to_string())); } let waiting = s.script_palette_event(id, event).map_err(|e| bad(C, e))?; diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index c635db0585..16c8458957 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -211,6 +211,9 @@ pub(crate) struct Dialogs { waiting: RefCell>, /// The error that ended the run when an answer could not reach the script. failed: RefCell>, + /// An answer could not reach the script, so a dialog still open when the run ends is listed + /// with the answer `"error"`. + answer_failed: Cell, records: RefCell>, record_bytes: Cell, count: Cell, @@ -234,6 +237,7 @@ impl Dialogs { answers: RefCell::new(answers.into()), waiting: RefCell::default(), failed: RefCell::default(), + answer_failed: Cell::new(false), records: RefCell::default(), record_bytes: Cell::new(0), count: Cell::new(0), @@ -282,6 +286,7 @@ impl Dialogs { self.window_waiting.set(false); if let Err(e) = realm.answer(event.data()) { *self.failed.borrow_mut() = Some(e); + self.answer_failed.set(true); } Ok(()) } @@ -446,18 +451,21 @@ impl Dialogs { *waiting = None; if let Err(e) = realm.answer(answer.data()) { *self.failed.borrow_mut() = Some(e); + self.answer_failed.set(true); } true } - /// The run ends while a dialog waits: the report lists it with the answer `"stop"`. + /// The run ends while a dialog waits: the report lists it with the answer `"stop"`, or + /// `"error"` when an answer could not reach the script. pub(crate) fn stopped(&self) { + let answer = if self.answer_failed.replace(false) { json!("error") } else { json!("stop") }; if let Some(d) = self.waiting.borrow_mut().take() { - self.record(&d, json!("stop")); + self.record(&d, answer.clone()); } self.window_waiting.set(false); if let Some(showing) = self.window.borrow_mut().take() { - self.end_record(&showing, json!("stop")); + self.end_record(&showing, answer); } } diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index e02e4727f1..b811c623b8 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -79,6 +79,9 @@ pub(crate) struct Queued { /// The file access scope of the request that gave the event, which its run keeps, narrowed to /// the scope in force when the run starts ([`crate::file_access::ScopeHandle::within_current`]). pub(crate) scope: crate::file_access::ScopeHandle, + /// The number of the request that gave the event last: an event that takes the place of a + /// waiting one takes a new number. + pub(crate) ticket: u64, } /// The palettes of a session, and the events that wait for a run. @@ -87,6 +90,13 @@ pub(crate) struct Palettes { list: Vec, waiting: VecDeque, last_id: u64, + /// The number the last event given took ([`Queued::ticket`]). + last_ticket: u64, + /// The number of the event whose run started last. + started_ticket: Option, + /// While [`Session::script_palette_run_waiting`] runs an event, the numbers of the events its + /// run takes inside it (`update()`). + taken_inline: Option>, /// The event the run that starts next handles ([`Session::script_palette_start`]). pub(crate) starting: Option, } @@ -187,15 +197,19 @@ impl Palettes { 0 }; let at = self.waiting.iter_mut().skip(after).rev().find(|q| q.palette == id && same_place(q, &event, element)); + let ticket = self.last_ticket.wrapping_add(1); if let Some(slot) = at.filter(|q| q.scope.same(&scope)) { slot.event = event; slot.list = list; + slot.ticket = ticket; + self.last_ticket = ticket; return Ok(Waiting::Merged); } if self.waiting.len() >= MAX_WAITING { return Err(format!("{MAX_WAITING} script palette events already wait; this one was not kept")); } - self.waiting.push_back(Queued { palette: id, event, element, list, grants: None, scope }); + self.waiting.push_back(Queued { palette: id, event, element, list, grants: None, scope, ticket }); + self.last_ticket = ticket; Ok(Waiting::Added) } @@ -253,7 +267,11 @@ impl Palettes { /// The oldest waiting event for a palette of the engine `engine`, which a palette's `update()` /// in a run of that engine takes and hands to the palette at once ([`Palettes::next_of`]). pub(crate) fn take_for(&mut self, engine: &str) -> Option { - self.next_of(engine).map(|(_, q)| q) + let q = self.next_of(engine).map(|(_, q)| q)?; + if let Some(taken) = self.taken_inline.as_mut() { + taken.push(q.ticket); + } + Some(q) } /// Whether an event waits for a palette of the engine `engine`, which [`Palettes::take_for`] @@ -383,10 +401,19 @@ impl Session { } /// Whether [`Session::script_palette_start`] can start a waiting event's run now: an event - /// waits, no run is going, and no undo group is open, which a run cannot start in. A drag in - /// progress is not counted, since starting the run settles it. + /// waits, no run is going, and no undo group is open, which a run cannot start in, nor a drag + /// in a document other than the active one. A drag in the active document is not counted, + /// since starting the run settles it. pub fn script_palette_can_start(&self) -> bool { - !self.script_palettes.waiting.is_empty() && !self.script_running() && !self.undo_group_open() + !self.script_palettes.waiting.is_empty() && !self.script_running() && !self.palette_run_blocked() + } + + /// Whether an open edit keeps a palette event's run from starting: an undo group, the + /// session's or a document's, or a drag in a document other than the active one (starting the + /// run settles a drag in the active one). + pub(crate) fn palette_run_blocked(&self) -> bool { + let active = self.active().map(|d| d.uid); + self.undo_group_open() || self.docs.iter().any(|d| d.interaction.is_some() && Some(d.uid) != active) } /// Whether an undo group is open, the session's or a document's, which a run cannot start in. @@ -410,6 +437,7 @@ impl Session { return None; } let (palette, mut queued) = self.script_palettes.next()?; + self.script_palettes.started_ticket = Some(queued.ticket); queued.grants = Some(palette.grants.clone()); let title = palette.dialog.title(); let name = if title.is_empty() { "palette".to_string() } else { super::dialogs::cut_to(title, super::dialogs::MAX_TITLE_BYTES).to_string() }; @@ -442,15 +470,29 @@ impl Session { } /// `script.palette.event` with no run going and nobody to ask: runs the waiting events in turn, - /// the one just given last. → that one's report. An event whose run could not begin, for - /// example because the recovery copies could not be saved, ends this with its error, and the - /// events after it keep waiting. + /// in their order in line. → the report of the event just given, wherever it waited, or an + /// error when it was dropped without a run. An event whose run could not begin, for example + /// because the recovery copies could not be saved, ends this, and the events after it keep + /// waiting: with its error, or with the given event's result when that one has run. pub(crate) fn script_palette_run_waiting(&mut self) -> Result { - let mut last = Err(EngineError::Other("no script palette event waits".into())); + let want = self.script_palettes.last_ticket; + let mut mine = None; while let Some(started) = self.script_palette_start() { - started?; - last = self.script_run_to_end(); + // A later event whose run cannot begin leaves the given event's result as it is. + if let Err(e) = started { + return mine.unwrap_or(Err(e)); + } + self.script_palettes.taken_inline = Some(Vec::new()); + let r = self.script_run_to_end(); + // A run of the same engine can take the event while it runs (`update()`): its report + // is then the event's. + let inline = self.script_palettes.taken_inline.take().is_some_and(|t| t.contains(&want)); + if mine.is_none() && (self.script_palettes.started_ticket == Some(want) || inline) { + mine = Some(r); + } } - last + mine.unwrap_or_else(|| { + Err(EngineError::Other("the script palette event was dropped without a run: its palette or control can no longer take it".into())) + }) } } diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 2618cd9083..0a253f0961 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -642,6 +642,19 @@ fn with_nobody_to_ask_an_event_whose_run_cannot_begin_ends_with_its_error_and_th assert_eq!(s.script_palette_run_waiting().unwrap()["log"], json!(["click 1"])); } +#[test] +fn with_nobody_to_ask_an_event_that_replaces_a_waiting_one_answers_with_its_own_report() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Change(2, crate::script::UiValue::Text("a".into()))), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + // The new change takes the waiting change's place, before the click. + let changed = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 2, "value": "z"})).unwrap(); + assert_eq!(changed["log"], json!(["change z"])); + assert_eq!(s.script_palette_events_waiting(), 0, "the click after it ran too"); +} + #[test] fn a_handler_s_error_keeps_its_file_when_a_palette_getter_throws_after_it() { let base = std::env::temp_dir().join(format!("vc-script-palette-place-{}", std::process::id())); diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 596ac62671..770f34957c 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -685,10 +685,19 @@ impl Realm { /// Gives the host's `paletteUpdate` the controls of each ScriptUI palette this realm keeps, as /// the run that just ended left them; nothing when it keeps none. A getter it reads runs in the - /// run's fuel, and what it throws ends the run. + /// run's fuel, at most [`Realm::set_unbroken_fuel`] of it, as a nested run that cannot pause + /// does; what it throws ends the run. pub fn refresh_script_ui(&mut self) -> Result<(), RunError> { - match crate::scriptui::refresh(&mut self.interp) { + let interp = &mut self.interp; + let total = interp.fuel; + let cap = self.unbroken_fuel.min(total); + interp.fuel = cap; + let r = crate::scriptui::refresh(interp); + let used = cap - interp.fuel; + interp.fuel = total - used; + match r { Ok(()) => Ok(()), + Err(Abrupt::Limit(LimitKind::Fuel)) if total > cap => self.outcome(Err(Abrupt::Limit(LimitKind::Unbroken))).map(drop), Err(e) => self.outcome(Err(e)).map(drop), } } diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 131db628db..bc05f207b8 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -1784,7 +1784,13 @@ pub(crate) fn refresh(i: &mut Interp) -> JsResult<()> { if i.script_ui.as_ref().is_none_or(|c| c.palettes.is_empty()) { return Ok(()); } - update_palettes(i) + // An `update()` that a getter calls now takes no waiting event, which waits for a run of its + // own. + let was = i.script_ui.as_ref().is_some_and(|c| c.taking); + set_taking(i, true); + let r = update_palettes(i); + set_taking(i, was); + r } /// A palette's `show()`: the host shows its description at once, then `onShow` runs, and `show()` @@ -1817,7 +1823,13 @@ fn palette_shown(i: &mut Interp, keep: &[Value], id: Value) -> JsResult { fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { let f = host_fn(i, "paletteEvent")?; let answer = i.call(&f, &Value::Undefined, &[])?; - deliver(i, answer)?; + // An `update()` that a handler calls while this event runs takes no waiting event, so a later + // event does not run before this one has finished. + let was = i.script_ui.as_ref().is_some_and(|c| c.taking); + set_taking(i, true); + let r = deliver(i, answer); + set_taking(i, was); + r?; Ok(Value::Undefined) } @@ -1872,7 +1884,16 @@ fn deliver(i: &mut Interp, answer: Value) -> JsResult { _ => None, }, }; - let Some(at) = at.filter(|&n| n >= 1 && n < held.len()) else { + // A getter read in the description may also have removed the control after the + // description listed it: no handler runs for it. + let gone = match at.filter(|&n| n >= 1 && n < held.len()) { + Some(n) => match held[n].as_object() { + Some(c) => !holds(i, win, c)?, + None => false, + }, + None => true, + }; + let Some(at) = at.filter(|_| !gone) else { return Err(error(i, "a palette event names a control the palette no longer holds")); }; set_slot(i, ev, "id", Value::Number(at as f64))?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index f3ef2c7840..2163026393 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -956,6 +956,24 @@ fn a_palette_event_finds_its_control_by_its_id() { assert_eq!(r.run("clicks").unwrap(), JsValue::Number(2.0)); } +#[test] +fn a_palette_click_on_a_button_a_getter_removed_runs_no_handler_and_throws() { + // The palette is element 1, the label 2 and the button 3. + let Data::Object(mut fields) = palette_event(1.0, click(2)) else { panic!("an event is an object") }; + fields.push(("element".into(), Data::Number(3.0))); + let (mut r, _) = palette_realm(vec![Data::Object(fields)]); + r.run( + "var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var b = p.add('button', undefined, 'Go'); \ + var clicks = 0; b.onClick = function () { clicks++; }; var armed = false; \ + Object.defineProperty(label, 'text', {get: function () { if (armed) { armed = false; p.remove(b); } return 'idle'; }}); p.show();", + ) + .unwrap(); + // The event reads the label's text for the palette's description, which removes the button. + let given = r.run("armed = true; try { Window.__vcPaletteEvent(); 'given'; } catch (e) { e.message; }").unwrap(); + assert_eq!(given, JsValue::String("a palette event names a control the palette no longer holds".into())); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(0.0), "the removed button's handler does not run"); +} + #[test] fn a_palette_event_does_not_run_a_handler_once_a_getter_closed_the_palette() { let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(2))]); diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index f984d0eeec..2b6091c4d9 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -729,7 +729,8 @@ pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { Some(parent) => { host.open_child(close_question(), parent); } - None if host.is_empty() => { + // The script's palettes stay open beside the question. + None if host.is_empty() || host.open_dialogs().iter().all(|d| d.key.as_deref() == Some(crate::script_palettes::KIND)) => { host.open(close_question()); } None => {} diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 074b2a5567..48401c4b57 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -239,6 +239,9 @@ pub(crate) fn commit_texts(w: &ScriptUiDialog, drafts: &mut BTreeMap Result<(), String> { let mut events = vec![check_event(w, event)?]; + // When the run does not take the first event, the typed texts stay in their fields. + let drafts = with_window(app, |d| d.drafts.clone()).unwrap_or_default(); if matches!(events[0], UiEvent::Click(_) | UiEvent::Close) { with_window(app, |d| d.commit_drafts(w, &mut events)).unwrap_or(Ok(()))?; } let mut events = events.into_iter(); - if let Some(first) = events.next() { - app.session.script_window_answer(first)?; + if let Some(first) = events.next() + && let Err(e) = app.session.script_window_answer(first) + { + with_window(app, |d| d.drafts = drafts); + return Err(e); } let later: Vec = events.filter_map(|e| queued(w, &e)).collect(); with_window(app, |d| { @@ -828,6 +840,8 @@ pub(crate) fn cancel(app: &mut VectorcraftApp) -> Result<(), String> { return with_window(app, |d| d.queue.push_back(Queued::Cancel)).ok_or_else(|| "no script dialog waits".to_string()); }; let mut events = vec![cancel_event(&w)]; + // When the run does not take the first event, the typed texts stay in their fields. + let drafts = with_window(app, |d| d.drafts.clone()).unwrap_or_default(); with_window(app, |d| d.commit_drafts(&w, &mut events)).unwrap_or(Ok(()))?; let empty = with_window(app, |d| d.queue.is_empty()).unwrap_or(true); // A cancel after other events goes last, and is a click on the cancel button of the dialog the @@ -837,8 +851,12 @@ pub(crate) fn cancel(app: &mut VectorcraftApp) -> Result<(), String> { events.pop(); } let mut events = events.into_iter(); - if empty && let Some(first) = events.next() { - app.session.script_window_answer(first)?; + if empty + && let Some(first) = events.next() + && let Err(e) = app.session.script_window_answer(first) + { + with_window(app, |d| d.drafts = drafts); + return Err(e); } let mut later: Vec = events.filter_map(|e| queued(&w, &e)).collect(); if deferred { diff --git a/docs/mcp.md b/docs/mcp.md index b05820412e..ecdcd662bf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3877,7 +3877,11 @@ the same controls, handlers and limits: Always. A file allowed once stays with the run whose dialog allowed it, as for any later run. - Each click, change or close the person gives a palette runs its handler as a run of its own in the palette's engine, with its own report and, when it changes a document, its own Run Script undo step. While another run - goes on, the event waits and runs after it; events run one at a time, oldest first. While an event waits, a + goes on, the event waits and runs after it; events run one at a time, oldest first. A run of the same engine + whose own code calls `update()` takes a waiting event inside that run instead: the event then has no report or + undo step of its own, and its changes are part of that run's. An `update()` in the handler of a palette event + that waited for a run of its own takes no waiting event, so the event waits until that run ends. With nobody to ask, `script.palette.event` answers + with the report of the run that handled the event it gave. While an event waits, a newer click on the same control, change of the same control or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access scope. Otherwise the new event waits at the end of the line (`merged: false`). A click or close takes its place only if no @@ -3901,10 +3905,12 @@ visible, controls: [{index, kind, name, text, enabled, visible, value?, items?, waitingLimit: 64}`. `script.palette.event {palette, event, control?, value?}` gives a shown palette a `click`, a `change` or a `close`, with `control` and `value` as in a `window` answer's step (`control` can also be a control's index). In the app it returns `{waiting: true, merged, waitingEvents}`, and the handler's report is later in -`ui.inspect`'s `scriptReport`. With nobody to ask, it runs the waiting events and returns the report of this one, -or its error; an event whose run cannot begin ends it with that error, and the events after it keep waiting. A -hidden palette, a disabled or hidden control, and a control that cannot take the event are errors, and with nobody -to ask so is an event while an undo group is open. +`ui.inspect`'s `scriptReport`. With nobody to ask, it runs the waiting events in order and returns the report of +the run that handled this one, or its error, even when it took the place of an earlier waiting event; an event +dropped without a run is an error. An event whose run cannot begin ends it with that error, or with this event's +result when this one has run, and the events after it keep waiting. A hidden palette, a disabled or hidden +control, and a control that cannot take the event are errors, and with nobody to ask so is an event while an undo +group or a drag in a document other than the active one is open. ```sh vectorcraft-cli run --cmd script.run --params '{"source": "#targetengine tools\nvar p = new Window(\"palette\", \"Tools\"); var go = p.add(\"button\", undefined, \"Add\"); go.onClick = function () { vc.run(\"shape.rectangle\", {x: 0, y: 0, width: 20, height: 20}); }; p.show();"}' From 77cc99b2bd3910633a97987b4f6c0b1e11a0e868 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 15:05:36 -0800 Subject: [PATCH 20/34] Scripts: palette refreshes run their getters' promise jobs, and events keep their place - A prompt, confirm or alert answer that cannot reach the script is listed in the report with the answer "error" instead of the answer given. - After a named-engine run, point changes that a palette getter makes while the palettes are refreshed are written before the run ends. - The promise jobs a palette getter queues during that refresh run in the same fuel, the host gets the controls once more after them, and their unhandled rejections are part of the run's report. An update() they call takes no waiting event. - A waiting text change merges with a newer one only when no click or close of its palette waits after it. - With nobody to ask, an open edit that cannot be finished before the run ends script.palette.event with that error, and the event does not wait. - A click whose onClick getter hid the palette runs no handler, and a list choice whose list a text getter removed, or whose earlier item text a later getter changed, is refused. - add() and remove() on a shown palette return their result when a getter throws while the host's copy is updated; the host gets the controls at the next update or when the run ends. - In the app, a palette event whose run cannot begin shows its own error instead of an earlier stopped run's message. - The overview comments, docs/mcp.md and the progress line describe the update() handling, the merge rule, onClose returning false and the named engine a palette needs. --- crates/engine/src/script/dialogs.rs | 21 ++-- crates/engine/src/script/mod.rs | 19 ++- crates/engine/src/script/palettes.rs | 23 ++-- crates/engine/src/tests/script_dialogs.rs | 24 ++++ crates/engine/src/tests/script_palettes.rs | 54 +++++++- crates/js/src/builtins/promise.rs | 5 + crates/js/src/realm.rs | 12 +- crates/js/src/scriptui.rs | 82 +++++++++--- crates/js/src/scriptui_tests.rs | 133 ++++++++++++++++++++ crates/ui-egui/src/script_palettes.rs | 16 +-- crates/ui-egui/src/tests/script_palettes.rs | 17 +++ docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 13 files changed, 366 insertions(+), 48 deletions(-) diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index 16c8458957..16803c1b77 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -439,19 +439,26 @@ impl Dialogs { } /// Gives the waiting dialog `answer`, which must be for its kind and, for a prompt, at most - /// [`MAX_PROMPT_BYTES`]. → false when it is not, or nothing waits. + /// [`MAX_PROMPT_BYTES`]. → false when it is not, or nothing waits. The report lists the dialog + /// with the answer, or with `"error"` when the answer could not reach the script. pub(crate) fn answer(&self, realm: &mut Realm, answer: DialogAnswer) -> bool { let fits = match &answer { DialogAnswer::Prompt(Some(t)) => t.len() <= MAX_PROMPT_BYTES, _ => true, }; let mut waiting = self.waiting.borrow_mut(); - let Some(d) = waiting.as_ref().filter(|d| d.kind == answer.kind() && fits) else { return false }; - self.record(d, answer.json()); - *waiting = None; - if let Err(e) = realm.answer(answer.data()) { - *self.failed.borrow_mut() = Some(e); - self.answer_failed.set(true); + if !waiting.as_ref().is_some_and(|d| d.kind == answer.kind() && fits) { + return false; + } + let Some(d) = waiting.take() else { return false }; + drop(waiting); + match realm.answer(answer.data()) { + Ok(()) => self.record(&d, answer.json()), + Err(e) => { + self.record(&d, json!("error")); + *self.failed.borrow_mut() = Some(e); + self.answer_failed.set(true); + } } true } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index b019ef2085..8456eb4f20 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -49,8 +49,9 @@ //! documents back and keeps the engine's globals; an internal error drops the engine. //! //! A run in a named engine can show ScriptUI palettes ([`palettes`]), which stay open after it and -//! whose events run as runs of their own in that engine, one at a time once no run is going. A -//! palette closes with its engine. +//! whose events run as runs of their own in that engine, one at a time once no run is going. A run +//! of that engine whose own code calls `update()` handles the waiting events inside the run +//! instead. A palette closes with its engine. pub mod actions; pub mod console; @@ -2219,6 +2220,10 @@ impl Session { /// A script can't start while a document holds a drag in progress or an undo group, which its /// one undo step could not take in. fn settle_for_script(&mut self) -> Result<()> { + #[cfg(test)] + if SETTLE_FAILS.with(Cell::get) { + return Err(EngineError::Other("the open edit could not be settled".into())); + } self.finish_tool_edit_later()?; if self.active().is_some() { cmd::settle_interaction(self)?; @@ -2935,8 +2940,12 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result realm.refresh_script_ui().map(|()| Progress::Done(v)), + // The palettes of a named engine show the controls as the run left them. A getter + // the refresh reads may change points, which are written before the run ends. + Ok(Progress::Done(v)) if named => realm.refresh_script_ui().and_then(|()| { + dom::flush(host).map_err(end_flush_error)?; + Ok(Progress::Done(v)) + }), // A failed run keeps its globals, so its palettes show what it left too; a refresh // that fails as well (the fuel is spent, a stop) leaves them as they were, and the // run's error keeps its place. @@ -3019,6 +3028,8 @@ thread_local! { pub(crate) static TEST_RESULT_BYTES: Cell> = const { Cell::new(None) }; /// Tests: makes the next slice panic. pub(crate) static PANIC_IN_SLICE: Cell = const { Cell::new(false) }; + /// Tests: makes settling the open edits before a run fail. + pub(crate) static SETTLE_FAILS: Cell = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. pub(crate) static TEST_GROWTH: Cell> = const { Cell::new(None) }; /// Tests: the bytes a run may keep in place of [`GROWTH_BYTES`]. diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index b811c623b8..e5cc8b6de5 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -189,13 +189,10 @@ impl Palettes { let element = control_of(&mut event).and_then(|c| p.dialog.nodes.get(*c)).map(|n| n.id); let scope = crate::file_access::ScopeHandle::capture(); // Only the most recent event for the same place can merge, in the same file access scope. - // A click or close merges only after its palette's last waiting change. + // A click or close merges only after its palette's last waiting change, and a change only + // after its palette's last waiting click or close. let closing = matches!(event, UiEvent::Click(_) | UiEvent::Close); - let after = if closing { - self.waiting.iter().rposition(|q| q.palette == id && matches!(q.event, UiEvent::Change(..))).map_or(0, |at| at + 1) - } else { - 0 - }; + let after = self.waiting.iter().rposition(|q| q.palette == id && matches!(q.event, UiEvent::Change(..)) == closing).map_or(0, |at| at + 1); let at = self.waiting.iter_mut().skip(after).rev().find(|q| q.palette == id && same_place(q, &event, element)); let ticket = self.last_ticket.wrapping_add(1); if let Some(slot) = at.filter(|q| q.scope.same(&scope)) { @@ -473,11 +470,21 @@ impl Session { /// in their order in line. → the report of the event just given, wherever it waited, or an /// error when it was dropped without a run. An event whose run could not begin, for example /// because the recovery copies could not be saved, ends this, and the events after it keep - /// waiting: with its error, or with the given event's result when that one has run. + /// waiting: with its error, or with the given event's result when that one has run. An open + /// edit that cannot be settled ends this with its error, and the given event no longer waits. pub(crate) fn script_palette_run_waiting(&mut self) -> Result { let want = self.script_palettes.last_ticket; let mut mine = None; - while let Some(started) = self.script_palette_start() { + loop { + if !self.script_running() + && !self.script_palettes.waiting.is_empty() + && let Err(e) = self.settle_for_script() + { + // A caller that gives the event again then does not give it twice. + self.script_palettes.waiting.retain(|q| q.ticket != want); + return mine.unwrap_or(Err(e)); + } + let Some(started) = self.script_palette_start() else { break }; // A later event whose run cannot begin leaves the given event's result as it is. if let Err(e) = started { return mine.unwrap_or(Err(e)); diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index baa8989208..0ebb346fe7 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -200,6 +200,30 @@ fn prompt_cancel_returns_null() { assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([true])); } +/// A prompt's answer that the engine's nearly full heap cannot hold ends the run, and the report +/// lists the prompt with the answer `"error"`, not the text that did not reach the script. +#[test] +fn a_prompt_answer_that_cannot_reach_the_script_is_listed_as_an_error() { + use crate::script::TEST_ENGINE_HEAP; + TEST_ENGINE_HEAP.with(|h| h.set(Some(8 << 20))); + let mut s = one_doc(); + let filled = headless( + &mut s, + "#targetengine full\nvar head = null, c = 'x';\nwhile (c.length < 4096) c += c;\nfor (var i = 0; ; i++) head = {s: c + i, n: head};", + json!([]), + ); + framed(&mut s, "#targetengine full\nvar a = prompt('Name', '');"); + let waited = pump(&mut s).is_none(); + let answered = s.script_answer(DialogAnswer::Prompt(Some("x".repeat(dialogs::MAX_PROMPT_BYTES)))); + let ended = pump(&mut s); + let report = s.script_report(); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + assert!(filled.unwrap_err().to_string().contains("Heap")); + assert!(waited && answered); + assert!(ended.unwrap().is_err(), "the answer did not fit in the heap"); + assert_eq!(report.unwrap()["dialogs"][0]["answer"], "error"); +} + #[test] fn dialog_loop_stops_or_exhausts() { let mut s = one_doc(); diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 0a253f0961..92a403894a 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; use crate::script::palettes::{MAX_PALETTES, MAX_WAITING}; use crate::script::scriptui::PALETTE_NEEDS_ENGINE; -use crate::script::{DialogAnswer, TEST_ELAPSED, UiEvent, Waiting}; +use crate::script::{DialogAnswer, SETTLE_FAILS, TEST_ELAPSED, UiEvent, Waiting}; use crate::*; /// One open document with one rectangle. @@ -642,6 +642,54 @@ fn with_nobody_to_ask_an_event_whose_run_cannot_begin_ends_with_its_error_and_th assert_eq!(s.script_palette_run_waiting().unwrap()["log"], json!(["click 1"])); } +#[test] +fn with_nobody_to_ask_an_event_whose_open_edit_cannot_be_settled_ends_with_that_error_and_does_not_wait() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + SETTLE_FAILS.with(|f| f.set(true)); + let r = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})); + let waiting = s.script_palette_events_waiting(); + SETTLE_FAILS.with(|f| f.set(false)); + let e = r.unwrap_err().to_string(); + assert!(e.contains("could not be settled"), "{e}"); + assert_eq!(waiting, 0, "the refused click does not wait to run later"); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"]), "only the click given after it ran"); +} + +#[test] +fn a_change_does_not_take_the_place_of_a_change_that_waits_before_a_click() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + let text = |t: &str| UiEvent::Change(2, crate::script::UiValue::Text(t.into())); + assert_eq!(s.script_palette_event(id, text("a")), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, text("b")), Ok(Waiting::Added), "the text typed after the click waits after it"); + assert_eq!(s.script_palette_event(id, text("c")), Ok(Waiting::Merged), "changes with no click between them still merge"); + let log = s.script_palette_run_waiting().unwrap()["log"].clone(); + assert_eq!(log, json!(["change c"])); + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn a_point_change_a_palette_getter_makes_after_the_run_is_kept() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine points\nvar armed = false; var p = new Window('palette'); p.add('button', undefined, 'Go'); \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; app.activeDocument.pathItems[0].pathPoints[0].anchor = [3, 4]; } return 'P'; }}); \ + p.show();", + ) + .unwrap(); + let before = format!("{:?}", s.documents()[0].doc.layers); + run(&mut s, "#targetengine points\narmed = true;").unwrap(); + assert_ne!(format!("{:?}", s.documents()[0].doc.layers), before, "the getter's point change was written"); + let anchor = run(&mut s, "vc.log(app.activeDocument.pathItems[0].pathPoints[0].anchor);").unwrap()["log"].clone(); + assert_eq!(anchor, json!([[3, 4]])); +} + #[test] fn with_nobody_to_ask_an_event_that_replaces_a_waiting_one_answers_with_its_own_report() { let mut s = one_doc(); @@ -777,9 +825,11 @@ fn an_erroring_handler_ends_its_run_and_leaves_the_palette_open() { ) .unwrap(); let id = only_palette(&s); + let art = format!("{:?}", s.documents()[0].doc.layers); let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); assert!(e.contains("broken"), "{e}"); - assert_eq!(s.documents()[0].history.undo.len(), before, "the failed handler's rectangle was rolled back"); + assert_eq!(format!("{:?}", s.documents()[0].doc.layers), art, "the failed handler's rectangle was rolled back"); + assert_eq!(s.documents()[0].history.undo.len(), before, "the failed handler adds no undo step"); assert_eq!(only_palette(&s), id); } diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 7f684fbbf5..54e5eda498 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -583,6 +583,11 @@ impl Interp { !self.frames.is_empty() || self.promises.draining } + /// Whether promise jobs wait to run. + pub(crate) fn jobs_waiting(&self) -> bool { + !self.promises.queue.is_empty() + } + /// Runs the queued jobs, and the jobs they queue, until the queue is empty, after the script's /// code ended with `completion`, which this gives back. pub(crate) fn drain_jobs(&mut self, completion: Value) -> JsResult { diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 770f34957c..f5f397878d 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -686,7 +686,9 @@ impl Realm { /// Gives the host's `paletteUpdate` the controls of each ScriptUI palette this realm keeps, as /// the run that just ended left them; nothing when it keeps none. A getter it reads runs in the /// run's fuel, at most [`Realm::set_unbroken_fuel`] of it, as a nested run that cannot pause - /// does; what it throws ends the run. + /// does; what it throws ends the run. The promise jobs a getter queues run in the same fuel, + /// and the host then gets the controls once more ([`crate::scriptui::refresh`]). Their + /// unhandled rejections join the run's ([`Realm::unhandled_rejections`]). pub fn refresh_script_ui(&mut self) -> Result<(), RunError> { let interp = &mut self.interp; let total = interp.fuel; @@ -696,7 +698,13 @@ impl Realm { let used = cap - interp.fuel; interp.fuel = total - used; match r { - Ok(()) => Ok(()), + Ok(()) => { + let (more, count) = self.interp.take_unhandled(); + let room = crate::builtins::promise::MAX_REPORTED.saturating_sub(self.rejections.0.len()); + self.rejections.0.extend(more.into_iter().take(room)); + self.rejections.1 += count; + Ok(()) + } Err(Abrupt::Limit(LimitKind::Fuel)) if total > cap => self.outcome(Err(Abrupt::Limit(LimitKind::Unbroken))).map(drop), Err(e) => self.outcome(Err(e)).map(drop), } diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index bc05f207b8..61e36c56d3 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -700,7 +700,7 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult } let item = add_item(i, o, &arg(args, 1))?; if let Some(win) = object_slot(i, o, WINDOW)? { - i.rooted(std::slice::from_ref(&item), |i| update_palette(i, win))?; + i.rooted(std::slice::from_ref(&item), |i| publish_palette(i, win))?; } return Ok(item); } @@ -833,7 +833,7 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult append(i, o, KIDS, "children", Value::Object(c), counts)?; // The host's copy of a shown palette keeps each control's place in the list, which events // name it by. - update_palette(i, win)?; + publish_palette(i, win)?; Ok(Value::Object(c)) })(); i.temp_roots.truncate(mark); @@ -1506,7 +1506,7 @@ fn remove(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult JsResult<()> { Ok(()) } +/// [`update_palette`] after an `add` or a `remove` that has already changed the palette: what a +/// getter throws while the palette is read does not take the place of the change's result. The +/// host gets the controls at the next update, or when the run ends ([`refresh`]). +fn publish_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { + match update_palette(i, win) { + // The exception no longer propagates, so a later error is reported at its own place. + Err(Abrupt::Throw(_)) => { + i.passing = Value::Undefined; + i.thrown_mark = None; + i.throw_site = None; + Ok(()) + } + r => r, + } +} + /// Gives the host the controls of every palette it shows, after a handler may have changed them. fn update_palettes(i: &mut Interp) -> JsResult<()> { // A getter may close a later palette, which removes it from the rooted list, so the copy is @@ -1779,18 +1795,32 @@ fn update_palettes(i: &mut Interp) -> JsResult<()> { } /// Gives the host the controls of every palette the realm keeps, as a run left them -/// ([`crate::Realm::refresh_script_ui`]); nothing without palettes. +/// ([`crate::Realm::refresh_script_ui`]). When the getters queued promise jobs, the jobs run and +/// the host gets the controls once more, and the jobs that second pass queues run too. An +/// `update()` that a getter or a job calls meanwhile takes no waiting event, which waits for a run +/// of its own. pub(crate) fn refresh(i: &mut Interp) -> JsResult<()> { + let was = i.script_ui.as_ref().is_some_and(|c| c.taking); + set_taking(i, true); + let r = (|| { + refresh_palettes(i)?; + if i.jobs_waiting() { + i.drain_jobs(Value::Undefined)?; + refresh_palettes(i)?; + i.drain_jobs(Value::Undefined)?; + } + Ok(()) + })(); + set_taking(i, was); + r +} + +/// Gives the host the controls of every palette the realm keeps, or does nothing without palettes. +fn refresh_palettes(i: &mut Interp) -> JsResult<()> { if i.script_ui.as_ref().is_none_or(|c| c.palettes.is_empty()) { return Ok(()); } - // An `update()` that a getter calls now takes no waiting event, which waits for a run of its - // own. - let was = i.script_ui.as_ref().is_some_and(|c| c.taking); - set_taking(i, true); - let r = update_palettes(i); - set_taking(i, was); - r + update_palettes(i) } /// A palette's `show()`: the host shows its description at once, then `onShow` runs, and `show()` @@ -1907,11 +1937,14 @@ fn deliver(i: &mut Interp, answer: Value) -> JsResult { /// Whether the window `win` still takes the event `ev`: a dialog (`keep` is `Some`) always does, /// and a palette only while the host shows it under the id the event names. A getter or a handler -/// run for the event may have closed the palette. +/// run for the event may have closed or hidden the palette. fn still_takes(i: &mut Interp, win: ObjId, ev: ObjId, keep: Option<&[Value]>) -> JsResult { if keep.is_some() { return Ok(true); } + if !slot(i, win, SHOWN)?.truthy() { + return Ok(false); + } let id = slot(i, ev, "palette")?; Ok(matches!((slot(i, win, PALETTE_ID)?, id), (Value::Number(a), Value::Number(b)) if a == b)) } @@ -2155,6 +2188,11 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, if !still_takes(i, win, ev, keep)? { return Ok(()); } + // A getter may have removed the list, which changes neither its + // revision nor the palette. + if !holds(i, win, c)? { + return Err(error(i, "a palette event names a control the palette no longer holds")); + } if revised || !same || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { return Err(error(i, "a palette's list changed before the person's choice was taken")); } @@ -2172,7 +2210,8 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, } /// Does the list `c` hold items with the texts in `seen` (an array of strings), in that order? True -/// when `seen` is not an array. +/// when `seen` is not an array. A text a later item's getter changes after it was compared counts +/// as a change. fn same_items(i: &mut Interp, c: ObjId, seen: &Value) -> JsResult { let Some(seen) = seen.as_object() else { return Ok(true) }; let seen = list_values(i, seen)?; @@ -2181,10 +2220,23 @@ fn same_items(i: &mut Interp, c: ObjId, seen: &Value) -> JsResult { return Ok(false); } i.rooted(&items, |i| { + let mut texts = Vec::with_capacity(items.len()); for (item, want) in items.iter().zip(&seen) { let Some(item) = item.as_object() else { return Ok(false) }; let text = get(i, item, "text")?; - if i.to_str(&text)?.to_rust_string() != i.to_str(want)?.to_rust_string() { + let text = i.to_str(&text)?.to_rust_string(); + if text != i.to_str(want)?.to_rust_string() { + return Ok(false); + } + texts.push((item, text)); + } + // Read again without running getters: only a text held as a plain value can be checked so. + for (item, text) in texts { + let now = match i.get_own_property(item, &key("text"))? { + Some(Prop::Data { value, .. }) if !matches!(value, Value::Object(_)) => value, + _ => continue, + }; + if i.to_str(&now)?.to_rust_string() != text { return Ok(false); } } diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 2163026393..52618cccf1 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -1033,6 +1033,139 @@ fn a_palette_event_does_not_run_a_handler_whose_getter_closed_the_palette() { assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); } +#[test] +fn a_palette_event_does_not_run_a_handler_whose_getter_hid_the_palette() { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; \ + Object.defineProperty(b, 'onClick', {get: function () { reads++; p.hide(); return function () { clicks++; }; }}); p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("[reads, clicks].join()").unwrap(), JsValue::String("1,0".into()), "the handler read from a hidden palette does not run"); +} + +#[test] +fn a_palette_list_change_runs_no_on_change_once_an_item_s_text_getter_removed_the_list() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The second read of the first item's text, which compares it with the items the person saw, + // removes the list from the palette. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ + Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.remove(l); } return 'a'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette event names a control the palette no longer holds".into())); + assert_eq!(r.run("[reads, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("2,,null".into())); +} + +#[test] +fn a_palette_list_change_throws_when_a_later_item_s_text_getter_changes_an_earlier_item_s_text() { + let (mut r, _) = palette_realm(vec![seen_list_change(0.0)]); + // The second read of the second item's text, which compares it with the items the person saw, + // changes the first item's text, which that comparison already took. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ + Object.defineProperty(l.items[1], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { l.items[0].text = 'z'; } return 'b'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into())); + assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into())); +} + +#[test] +fn an_add_whose_palette_update_a_getter_breaks_still_returns_the_control() { + let (mut r, _) = palette_realm(Vec::new()); + r.run( + "var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var armed = false; \ + Object.defineProperty(label, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'idle'; }}); \ + var list = p.add('listbox', undefined, ['a']); p.show();", + ) + .unwrap(); + let added = r + .run( + "armed = true; var c, d, m = []; try { c = p.add('button', undefined, 'New'); } catch (e) { m.push(e.message); } \ + try { d = list.add('item', 'b'); } catch (e) { m.push(e.message); } \ + try { list.remove(0); } catch (e) { m.push(e.message); } \ + try { p.remove(c); } catch (e) { m.push(e.message); } armed = false; \ + [String(c && c.text), String(d && d.text), list.items.length, p.children.length, m.length].join()", + ) + .unwrap(); + assert_eq!(added, JsValue::String("New,b,1,2,0".into()), "each change is made once and gives its result"); + // A later error is at its own line, not at the getter's. + let e = r.run("armed = true;\np.add('button', undefined, 'Other');\narmed = false;\nthrow new Error('later');").unwrap_err(); + assert_eq!((e.message.contains("later"), e.line), (true, 4), "{e:?}"); +} + +#[test] +fn promise_jobs_a_palette_getter_queues_while_the_palette_is_refreshed_run() { + let (mut r, calls) = palette_realm(Vec::new()); + r.add_es2015(); + r.run( + "var ran = 0, armed = false; var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; \ + Promise.resolve().then(function () { ran++; b.text = 'Done'; }); Promise.reject(new Error('late')); } return 'P'; }}); \ + p.show(); armed = true;", + ) + .unwrap(); + let before = count(&calls, "paletteUpdate"); + r.refresh_script_ui().unwrap(); + assert_eq!(count(&calls, "paletteUpdate") - before, 2, "the host gets the controls again after the jobs ran"); + assert_eq!(r.unhandled_rejections().len(), 1, "the job's rejection is the run's"); + assert_eq!(r.run("[ran, b.text].join()").unwrap(), JsValue::String("1,Done".into()), "the job the getter queued ran with the refresh"); +} + +#[test] +fn promise_jobs_a_palette_getter_queues_on_every_refresh_run_without_another_refresh() { + let (mut r, calls) = palette_realm(Vec::new()); + r.add_es2015(); + r.run( + "var n = 0, reads = 0; var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); \ + Object.defineProperty(p, 'text', {get: function () { reads++; \ + Promise.resolve().then(function () { n++; }); return 'Title'; }});", + ) + .unwrap(); + let before = count(&calls, "paletteUpdate"); + r.refresh_script_ui().unwrap(); + assert_eq!(count(&calls, "paletteUpdate") - before, 2, "the host gets the controls again once after the jobs run"); + assert_eq!(r.run("reads > 0 && n === reads").unwrap(), JsValue::Bool(true), "every getter read's job runs before the refresh returns"); +} + +#[test] +fn promise_jobs_a_palette_getter_queues_during_refresh_leave_waiting_clicks_queued() { + let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new()); + r.add_es2015(); + r.run( + "var clicks = 0, jobs = 0, armed = false; var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { clicks++; }; \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { \ + Promise.resolve().then(function () { jobs++; p.update(); }); } return 'P'; }}); \ + p.show(); armed = true;", + ) + .unwrap(); + r.refresh_script_ui().unwrap(); + assert_eq!(count(&calls, "paletteTake"), 0, "the refresh leaves the waiting click queued"); + assert_eq!(r.run("jobs > 0 && clicks === 0").unwrap(), JsValue::Bool(true), "the promise jobs run without dispatching the click"); + assert_eq!(r.run("armed = false; p.update(); clicks").unwrap(), JsValue::Number(1.0), "a later update takes the waiting click"); + assert_eq!(count(&calls, "paletteTake"), 1, "the refresh restores the event-taking guard"); +} + +#[test] +fn an_object_on_close_throws_stays_whole_while_the_close_ends() { + let (mut r, _) = palette_realm(vec![palette_event(1.0, close())]); + r.run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.onClose = function () { throw {tag: 'kept'}; }; p.show();").unwrap(); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true)); + let thrown = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { String(e.tag); }"); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false)); + assert_eq!(thrown.unwrap(), JsValue::String("kept".into())); +} + #[test] fn a_palette_list_change_is_dropped_once_an_item_s_text_getter_closed_the_palette_and_on_close_changed_the_list() { let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index e5f71acac2..2aca10aa9b 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -2,12 +2,13 @@ //! ([`vectorcraft_engine::script::palettes`]): each shown palette is a modeless dialog on the //! window's dialog host (kind `scriptPalette`) that stays open after the run, with the controls the //! engine laid out. A click, a change or the close box waits in the session's line and runs as a -//! script run of its own once no run is going ([`crate::script_runs::poll`]); the palette stays -//! usable while a run goes on, and its events wait for it. A palette does not take the keyboard -//! focus when it opens or changes. An edit field's text is given when it loses the focus, at Enter -//! in a one-line field, or before a click or a close; a text the script would refuse, or that the -//! full line refuses, stays in its field with the error in the status bar, and the click or close -//! after it is not given. +//! script run of its own once no run is going ([`crate::script_runs::poll`]), unless a run of the +//! palette's engine calls `update()` in its own code first and handles it inside that run; the +//! palette stays usable while a run goes on, and its events wait for it. A palette does not take +//! the keyboard focus when it opens or changes. An edit field's text is given when it loses the +//! focus, at Enter in a one-line field, or before a click or a close; a text the script would +//! refuse, or that the full line refuses, stays in its field with the error in the status bar, and +//! the click or close after it is not given. //! //! The dialog's body has no app, so it keeps what the person did, and [`show`] follows the //! session's palettes into the host each frame and puts the events in line. @@ -364,12 +365,13 @@ pub(crate) fn with_palette(app: &VectorcraftApp, id: u64, f: impl FnOnce(&mut } /// Starts the run of the oldest waiting palette event when no run is going. → whether one started. +/// A run that could not begin shows its own error: the last report is an earlier run's. pub(crate) fn start_next(app: &mut VectorcraftApp) -> bool { match app.session.script_palette_start() { None => false, Some(Ok(_)) => true, Some(Err(e)) => { - crate::script_runs::failed(app, e.to_string()); + app.status(e.to_string()); false } } diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index f45977156c..a432f637a3 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -623,6 +623,23 @@ fn a_click_waiting_for_an_open_undo_group_asks_for_no_frames_and_runs_after_it() assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked"])); } +#[test] +fn a_click_whose_run_cannot_begin_after_a_stopped_run_shows_its_own_error() { + let mut app = app(); + let id = shown(&mut app, TOOLS); + start(&mut app, "while (true) {}"); + script_runs::poll(&mut app); + assert!(app.session.script_abandon()); + assert_eq!(app.session.script_report().unwrap()["kind"], "stopped"); + // The document has changes, and the session has nowhere to keep a recovery copy of it. + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.session.script_copy_first = true; + give(&app, id, UiEvent::Click(1)); + follow(&mut app); + assert!(!script_palettes::start_next(&mut app)); + assert!(app.ui.status.contains("recovery copy"), "{}", app.ui.status); +} + #[test] fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 8d88078074..bf95f272ea 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3895,7 +3895,8 @@ the same controls, handlers and limits: newer click on the same control, change of the same control or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access scope. Otherwise the new event waits at the end of the line (`merged: false`). A click or close takes its place only if no - change of its palette waits after it; otherwise it waits as a new event (`merged: false`). A text typed in + change of its palette waits after it, and a change takes its place only if no click or close of its palette waits + after it; otherwise it waits as a new event (`merged: false`). A text typed in a field goes to the script under what both its typing scope and the scope that commits it allow. A click or close waits under what its scope and all the texts it commits allow. A text edited in several scopes goes under what all of them allow. A waiting click or change, and a text typed in a field, stay with their control when a @@ -3918,7 +3919,8 @@ index). In the app it returns `{waiting: true, merged, waitingEvents}`, and the `ui.inspect`'s `scriptReport`. With nobody to ask, it runs the waiting events in order and returns the report of the run that handled this one, or its error, even when it took the place of an earlier waiting event; an event dropped without a run is an error. An event whose run cannot begin ends it with that error, or with this event's -result when this one has run, and the events after it keep waiting. A hidden palette, a disabled or hidden +result when this one has run, and the events after it keep waiting. When an open edit cannot be finished before +a run, it ends with that error and this event no longer waits. A hidden palette, a disabled or hidden control, and a control that cannot take the event are errors, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7fc6a2d9e8..d277392543 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1184,7 +1184,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`). - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person and runs the controls' `onClick`, `onChanging` and `onChange` handlers. The window's own callbacks are `onShow`, which runs when `show()` starts, and `onClose`, which runs before the dialog closes and keeps it open when it returns false. `show()` returns the result of `close(result)`, or 1 for the default button and 2 for the cancel button when the button has no `onClick` or click listener and no handler closed the dialog with another result. Controls also take `notify`, size objects a script can set one side of, lists' `find` and `remove`, and `addEventListener` for clicks and changes, which the dialog also takes for `show`; `Window.alert`, `Window.confirm` and `Window.prompt` open the script dialogs; a run over MCP or the command line takes the clicks and changes from a `window` answer. `new Window` and `add` also build a window or a control and the controls inside it from a resource specification (https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/). Other control types throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`. - - Scripts: ScriptUI's `new Window("palette")` in a script with `#targetengine` shows a palette that stays open beside the documents after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going; a newer event for the same control, given under the same file access scope, takes a waiting one's place. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes whose file access scopes cover the run's scope, so a Cancel button can stop a loop; an event given under narrower roots or another script gate waits for a run of its own instead. `update()` in the script's own code in the app also pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. A palette closes with `close()`, its close box, or the end of its engine or the session; at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.rs`. + - Scripts: ScriptUI's `new Window("palette")` makes a palette in a script whose `#targetengine` names an engine other than `main`, and the palette's `show()` shows it beside the documents, where it stays open after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going. A newer change for the same control takes a waiting change's place only when no click or close of that palette waits after the waiting change, and a newer click or close takes a waiting one's place only when no change of that palette waits after it; in both cases the two must be given under the same file access scope. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes whose file access scopes cover the run's scope, so a Cancel button can stop a loop; an event given under narrower roots or another script gate waits for a run of its own instead. `update()` in the script's own code in the app also pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. `close()` and the close box close a palette unless its `onClose` returns `false`; the end of its engine or the session closes it too. A session keeps at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.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`). From 95847e92dbbeba3a22e0949e953aaf53d3c0bf6b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 16:13:14 -0800 Subject: [PATCH 21/34] Scripts: palette handlers play the showing run's actions, and a given text stays in its field - A palette's handler runs take the actions of the run that first showed the palette (script.run's actions, or the Actions panel's in the app), so app.doScript in a handler plays them after that run ends too. - An edit field keeps showing the text it gave the script while that change waits for a run. The text goes once the session no longer holds the change, or the field holds the text; a text the script refuses goes back in the field as typed. --- crates/engine/src/script/palettes.rs | 32 ++++++++-- crates/engine/src/script/scriptui.rs | 2 +- crates/engine/src/tests/script_palettes.rs | 16 +++++ crates/ui-egui/src/script_palettes.rs | 61 +++++++++++++++--- crates/ui-egui/src/tests/script_palettes.rs | 69 +++++++++++++++++++++ docs/mcp.md | 4 +- 6 files changed, 171 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index e5cc8b6de5..9e5c5d1ca2 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -24,6 +24,7 @@ use std::collections::VecDeque; use serde_json::{Map, Value, json}; +use super::actions::Playable; use super::scriptui::{self, ScriptUiDialog, UiEvent, UiKind, UiValue}; use crate::{EngineError, Result, Session}; @@ -88,6 +89,9 @@ pub(crate) struct Queued { #[derive(Debug, Default)] pub(crate) struct Palettes { list: Vec, + /// The actions `app.doScript` plays in each palette's handlers, by palette id: those of the + /// run that first showed the palette. + actions: Vec<(u64, Vec)>, waiting: VecDeque, last_id: u64, /// The number the last event given took ([`Queued::ticket`]). @@ -124,12 +128,13 @@ impl Palettes { self.list.iter_mut().find(|p| p.id == id && p.engine == engine) } - /// `show()`: shows the palette `id` of `engine` with `dialog`, or a new one without `id`. → its id. + /// `show()`: shows the palette `id` of `engine` with `dialog`, or a new one without `id`, whose + /// handlers take the showing run's `actions`. → its id. pub(crate) fn show( &mut self, id: Option, engine: &str, - (file, grants): (Option, String), + (file, grants, actions): (Option, String, &[Playable]), dialog: ScriptUiDialog, ) -> std::result::Result { if let Some(p) = id.and_then(|id| self.find(id, engine)) { @@ -142,6 +147,9 @@ impl Palettes { } self.last_id += 1; self.list.push(ScriptPalette { id: self.last_id, engine: engine.to_string(), file, dialog, visible: true, grants }); + if !actions.is_empty() { + self.actions.push((self.last_id, actions.to_vec())); + } Ok(self.last_id) } @@ -165,7 +173,11 @@ impl Palettes { let before = self.list.len(); self.list.retain(|p| !(p.id == id && p.engine == engine)); self.waiting.retain(|q| q.palette != id); - self.list.len() != before + let closed = self.list.len() != before; + if closed { + self.actions.retain(|(p, _)| *p != id); + } + closed } /// Closes the palettes of the engines `keep` does not keep, with their waiting events. @@ -173,6 +185,7 @@ impl Palettes { self.list.retain(|p| keep(&p.engine)); let open: Vec = self.list.iter().map(|p| p.id).collect(); self.waiting.retain(|q| open.contains(&q.palette)); + self.actions.retain(|(p, _)| open.contains(p)); } /// Puts `event` for the shown palette `id` in line, once it is checked against the palette. @@ -397,6 +410,16 @@ impl Session { self.script_palettes.waiting.len() } + /// The changes that wait for a run, as (palette id, the id of the control they change). + pub fn script_palette_changes_waiting(&self) -> Vec<(u64, u64)> { + self.script_palettes + .waiting + .iter() + .filter(|q| matches!(q.event, UiEvent::Change(..))) + .filter_map(|q| q.element.map(|e| (q.palette, e))) + .collect() + } + /// Whether [`Session::script_palette_start`] can start a waiting event's run now: an event /// waits, no run is going, and no undo group is open, which a run cannot start in, nor a drag /// in a document other than the active one. A drag in the active document is not counted, @@ -439,6 +462,7 @@ impl Session { let title = palette.dialog.title(); let name = if title.is_empty() { "palette".to_string() } else { super::dialogs::cut_to(title, super::dialogs::MAX_TITLE_BYTES).to_string() }; let locale = super::dollar::ui_locale(self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language)); + let actions = self.script_palettes.actions.iter().find(|(id, _)| *id == palette.id).map(|(_, a)| a.clone()).unwrap_or_default(); let request = super::Request { name, name_given: true, @@ -450,7 +474,7 @@ impl Session { locale, answers: Vec::new(), module: false, - actions: Vec::new(), + actions, }; // The run takes the scope of the request that gave the event, within the scope in force now. let scope = queued.scope.clone().within_current(); diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index 1bd9bb8b2e..522a0e99d8 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -767,7 +767,7 @@ fn palette_show(host: &Host, args: &[Data]) -> Result { let dialog = described(host, args)?; let id = palette_id(args.get(1)); let grants = host.disk.borrow().own().to_string(); - let shown = host.session.borrow_mut().script_palettes.show(id, &engine, (host.file.clone(), grants), dialog); + let shown = host.session.borrow_mut().script_palettes.show(id, &engine, (host.file.clone(), grants, &host.actions), dialog); shown.map(|id| Data::Number(id as f64)).map_err(HostError::Range) } diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 92a403894a..f001f281d8 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -658,6 +658,22 @@ fn with_nobody_to_ask_an_event_whose_open_edit_cannot_be_settled_ends_with_that_ assert_eq!(clicked["log"], json!(["click 1"]), "only the click given after it ran"); } +#[test] +fn a_handler_plays_the_actions_of_the_run_that_showed_its_palette() { + let mut s = one_doc(); + let actions = + json!([{"set": "Set", "name": "Box", "steps": [{"command": "shape.rectangle", "params": {"x": 40, "y": 0, "width": 5, "height": 5}}]}]); + let source = "#targetengine acts\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { app.doScript('Box', 'Set'); vc.log('played'); }; p.show();"; + s.execute("script.run", &json!({"source": source, "name": "p.js", "actions": actions})).unwrap(); + let id = only_palette(&s); + let objects = |s: &Session| s.documents()[0].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::(); + let before = objects(&s); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap(); + assert_eq!(clicked["log"], json!(["played"])); + assert_eq!(objects(&s), before + 1, "the action drew its rectangle"); +} + #[test] fn a_change_does_not_take_the_place_of_a_change_that_waits_before_a_click() { let mut s = one_doc(); diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index 2aca10aa9b..08521de89c 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -46,19 +46,39 @@ pub(crate) struct PaletteWindow { /// and a list's change with the items the person saw, so a run that changes the palette before /// the app takes them leaves each with its own control. given: Vec<(ScopeHandle, ScopeHandle, Vec)>, + /// The text each edit field gave the script, by the field's id, while its change waits: the + /// field shows it until the palette's field holds it or no event waits. + pending: BTreeMap, open: bool, } impl PaletteWindow { fn new(palette: ScriptPalette) -> Self { - PaletteWindow { palette, drafts: BTreeMap::new(), draft_scopes: BTreeMap::new(), given: Vec::new(), open: true } + PaletteWindow { palette, drafts: BTreeMap::new(), draft_scopes: BTreeMap::new(), given: Vec::new(), pending: BTreeMap::new(), open: true } } /// The palette as the session has it now. A typed text whose field the palette no longer has is - /// dropped. - fn sync(&mut self, palette: ScriptPalette) { + /// dropped, and so is a given text once the field holds it, or once its change no longer waits + /// in the session (`waiting`: [`vectorcraft_engine::Session::script_palette_changes_waiting`]). + fn sync(&mut self, palette: ScriptPalette, waiting: &[(u64, u64)]) { self.palette = palette; script_window::keep_fields(&self.palette.dialog, &mut self.drafts); + let (nodes, palette, given) = (&self.palette.dialog.nodes, self.palette.id, !self.given.is_empty()); + self.pending.retain(|id, text| (given || waiting.contains(&(palette, *id))) && nodes.iter().any(|n| n.id == *id && n.text != *text)); + } + + /// Draws the palette's controls in `ui` and takes what the person did, as its body does. + #[cfg(test)] + pub(crate) fn paint(&mut self, ui: &mut Ui) { + let pass = script_window::controls(ui, &shown_dialog(&self.palette.dialog, &self.pending), &self.drafts, true); + self.take_pass(pass.drafts.into_iter().collect(), pass.events); + } + + /// The text edit field `i` shows. + #[cfg(test)] + pub(crate) fn shown_text(&self, i: usize) -> Option { + let id = self.palette.dialog.nodes.get(i)?.id; + self.drafts.get(&id).cloned().or_else(|| shown_dialog(&self.palette.dialog, &self.pending).nodes.get(i).map(|n| n.text.clone())) } /// The text typed in edit field `i` that the script has not had yet. @@ -123,6 +143,13 @@ impl PaletteWindow { } } } + for e in &events { + if let UiEvent::Change(i, UiValue::Text(text)) = e + && let Some(n) = self.palette.dialog.nodes.get(*i) + { + self.pending.insert(n.id, text.clone()); + } + } self.record(&events, &committed); } @@ -184,15 +211,16 @@ impl StackDialog for PaletteWindow { fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let heading = script_window::heading(&self.palette.dialog); - let PaletteWindow { palette, drafts, open, .. } = self; - let (palette, drafts_now) = (&*palette, &*drafts); + let PaletteWindow { palette, drafts, pending, open, .. } = self; + let dialog = shown_dialog(&palette.dialog, pending); + let drafts_now = &*drafts; // The body can run twice in a pass (measure, then paint), so the last run's report is // applied after the container. let shown = Dialog::new(heading) .modeless() .initial_focus(Initial::Keep) .opened(Bind::bound(open)) - .show(ui, |ui, _| script_window::controls(ui, &palette.dialog, drafts_now, true)); + .show(ui, |ui, _| script_window::controls(ui, &dialog, drafts_now, true)); let pass = shown.inner.unwrap_or_default(); let mut events = pass.events; // The close box gives the script the close; the palette stays open until the script closes @@ -206,6 +234,21 @@ impl StackDialog for PaletteWindow { } } +/// The controls of `dialog` as the fields show them: a given text whose change waits (`pending`) +/// stands in for its field's text. +fn shown_dialog<'a>(dialog: &'a ScriptUiDialog, pending: &BTreeMap) -> std::borrow::Cow<'a, ScriptUiDialog> { + if pending.is_empty() { + return std::borrow::Cow::Borrowed(dialog); + } + let mut dialog = dialog.clone(); + for n in &mut dialog.nodes { + if let Some(text) = pending.get(&n.id) { + n.text.clone_from(text); + } + } + std::borrow::Cow::Owned(dialog) +} + /// Follows the session's shown palettes into the dialog host: opens a palette that shows, updates /// one that changed and closes one that was hidden or closed. Then puts the events the person gave /// each palette in line. @@ -215,6 +258,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // which stays the top dialog and takes its answers. let s = &app.session; let modal = s.script_window().is_some() || s.script_dialog().is_some() || s.script_picker().is_some() || s.script_waiting(); + let waiting = s.script_palette_changes_waiting(); let taken = with_host(app, |host, ctx| { let ids: Vec = shown.iter().map(|p| palette_id(p.id)).collect(); for d in host.open_dialogs() { @@ -227,7 +271,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { for p in &shown { match host.get_mut_by_id::(palette_id(p.id)) { Some(w) => { - w.sync(p.clone()); + w.sync(p.clone(), &waiting); taken.push((p.id, std::mem::take(&mut w.drafts), std::mem::take(&mut w.draft_scopes), std::mem::take(&mut w.given))); } None if !modal => { @@ -257,6 +301,9 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { draft_scopes.retain(|field, _| drafts.contains_key(field)); with_host(app, |host, _| { if let Some(w) = host.get_mut_by_id::(palette_id(id)) { + // A refused text goes back in its field as typed, so the field does not show it as + // given. + w.pending.retain(|field, _| !drafts.contains_key(field)); w.drafts = drafts; w.draft_scopes = draft_scopes; } diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index a432f637a3..201b6c01d0 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -623,6 +623,75 @@ fn a_click_waiting_for_an_open_undo_group_asks_for_no_frames_and_runs_after_it() assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked"])); } +#[test] +fn a_given_text_stays_in_its_field_while_its_change_waits_for_a_run() { + let mut app = app(); + let source = "#targetengine fields\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'old'); \ + t.onChange = function () { vc.log(t.text); }; p.show();"; + let id = shown(&mut app, source); + start(&mut app, "while (true) {}"); + script_runs::poll(&mut app); + assert!(app.session.script_running()); + with_palette(&app, id, |w| w.commit_text(1, "new")).unwrap(); + follow(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 1, "the change waits for the run"); + follow(&mut app); + let shown = |app: &VectorcraftApp| with_palette(app, id, |w| w.shown_text(1)).flatten(); + assert_eq!(shown(&app).as_deref(), Some("new"), "the field keeps the given text while its change waits"); + assert!(app.session.script_abandon()); + assert!(script_palettes::start_next(&mut app)); + run_to_end(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["new"])); + follow(&mut app); + follow(&mut app); + assert_eq!(shown(&app).as_deref(), Some("new"), "the field holds the text the script took"); +} + +#[test] +fn a_given_text_leaves_its_field_once_a_running_update_took_its_change() { + let mut app = app(); + let source = "#targetengine fields\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'old'); \ + var b = p.add('button', undefined, 'Go'); t.onChange = function () { t.text = t.text.toUpperCase(); }; \ + b.onClick = function () {}; p.show();"; + let id = shown(&mut app, source); + start(&mut app, "#targetengine fields\nwhile (true) { p.update(); }"); + script_runs::poll(&mut app); + with_palette(&app, id, |w| w.commit_text(1, "new")).unwrap(); + follow(&mut app); + // The palette's controls go to the app before the click after the change is taken. + give(&app, id, UiEvent::Click(2)); + follow(&mut app); + for _ in 0..10_000 { + if app.session.script_palette_events_waiting() == 0 { + break; + } + script_runs::poll(&mut app); + } + assert_eq!(app.session.script_palette_events_waiting(), 0, "update() took both events"); + assert!(app.session.script_running()); + follow(&mut app); + let shown = with_palette(&app, id, |w| w.shown_text(1)).flatten(); + assert_eq!(shown.as_deref(), Some("NEW"), "the field shows the text the handler set"); + assert!(app.session.script_abandon()); +} + +#[test] +fn a_given_text_the_script_refuses_stays_in_its_field_after_the_next_pass() { + let mut app = app(); + let source = "#targetengine fields\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'old'); p.show();"; + let id = shown(&mut app, source); + let long = "x".repeat(crate::dialogs::script_window::DRAFT_CHARS / 2 + 1); + with_palette(&app, id, |w| w.commit_text(1, &long)).unwrap(); + follow(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 0, "the text is too long for the script"); + let ctx = app.ui_ctx.clone().unwrap(); + crate::testing::part_frame(&mut app, &ctx, egui::RawInput::default(), |app, ui| { + with_palette(app, id, |w| w.paint(ui)); + }); + follow(&mut app); + assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).flatten().as_deref(), Some(long.as_str())); +} + #[test] fn a_click_whose_run_cannot_begin_after_a_stopped_run_shows_its_own_error() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index bf95f272ea..593e187be1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3884,7 +3884,9 @@ the same controls, handlers and limits: On a palette that `hide()` hid, or that is not shown, it throws an `Error`; setting the palette's `visible` does not change this. A handler's run reads and writes the files the person allowed the script that first showed the palette with - Always. A file allowed once stays with the run whose dialog allowed it, as for any later run. + Always. A file allowed once stays with the run whose dialog allowed it, as for any later run. Its + `app.doScript` plays the actions the run that first showed the palette had (`script.run`'s `actions`, or in + the app the Actions panel's actions when the palette was first shown). - Each click, change or close the person gives a palette runs its handler as a run of its own in the palette's engine, with its own report and, when it changes a document, its own Run Script undo step. While another run goes on, the event waits and runs after it; events run one at a time, oldest first. A run of the same engine From 8069c92d3553ab7886b5b6e348fc992120e41235 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 18:13:28 -0800 Subject: [PATCH 22/34] Scripts: a typed text that a click gives stays in its field while it waits When a click or close on a palette gives a field's typed text, the field keeps showing that text while the change waits for a run, as a text the field gave on its own already does. Before, the field went back to its old text until the change ran. --- crates/ui-egui/src/script_palettes.rs | 12 +++++++++++- crates/ui-egui/src/tests/script_palettes.rs | 19 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index 08521de89c..4fff70f1c4 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -288,10 +288,13 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // Each event goes to its control as the palette is now; one whose control is gone, or whose // list's items changed since the person chose, is dropped. let mut change_refused = false; + // Texts whose change went in line, typed ones a click or close gave included: the field + // shows each until its change no longer waits. + let mut accepted = BTreeMap::new(); for (pass_scope, scope, given) in given { let mut events: Vec = given.into_iter().filter_map(|q| script_window::resolved(&p.dialog, q)).collect(); for (event_scope, event) in drafted(app, &p.dialog, &mut drafts, &mut events, &scope, &pass_scope, &draft_scopes) { - event_scope.run(|| give(app, ctx, p, &mut drafts, vec![event], &mut change_refused)); + event_scope.run(|| give(app, ctx, p, &mut drafts, vec![event], &mut change_refused, &mut accepted)); } // A text that went back in its field without a scope of its own takes this one. for field in drafts.keys() { @@ -303,6 +306,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if let Some(w) = host.get_mut_by_id::(palette_id(id)) { // A refused text goes back in its field as typed, so the field does not show it as // given. + w.pending.extend(accepted); w.pending.retain(|field, _| !drafts.contains_key(field)); w.drafts = drafts; w.draft_scopes = draft_scopes; @@ -372,6 +376,7 @@ fn give( drafts: &mut BTreeMap, events: Vec, change_refused: &mut bool, + accepted: &mut BTreeMap, ) { for e in events { if *change_refused && matches!(e, UiEvent::Click(_) | UiEvent::Close) { @@ -390,6 +395,11 @@ fn give( { drafts.remove(&n.id); } + if let Some((i, Some(text))) = change + && let Some(n) = p.dialog.nodes.get(i) + { + accepted.insert(n.id, text); + } ctx.request_repaint(); } Err(error) => { diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 201b6c01d0..52c143ff61 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -647,6 +647,25 @@ fn a_given_text_stays_in_its_field_while_its_change_waits_for_a_run() { assert_eq!(shown(&app).as_deref(), Some("new"), "the field holds the text the script took"); } +#[test] +fn a_typed_text_a_click_gives_stays_in_its_field_while_its_change_waits_for_a_run() { + let mut app = app(); + let source = "#targetengine fields\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'old'); \ + var b = p.add('button', undefined, 'Go'); b.onClick = function () { vc.log(t.text); }; p.show();"; + let id = shown(&mut app, source); + start(&mut app, "while (true) {}"); + script_runs::poll(&mut app); + assert!(app.session.script_running()); + with_palette(&app, id, |w| w.type_text(1, "new")).unwrap(); + give(&app, id, UiEvent::Click(2)); + follow(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 2, "the typed change and the click wait for the run"); + follow(&mut app); + let shown = with_palette(&app, id, |w| w.shown_text(1)).flatten(); + assert_eq!(shown.as_deref(), Some("new"), "the field keeps the typed text the click gave"); + assert!(app.session.script_abandon()); +} + #[test] fn a_given_text_leaves_its_field_once_a_running_update_took_its_change() { let mut app = app(); From d091abbf53113d907c98865b62de20a8885e9180 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 21:45:22 -0800 Subject: [PATCH 23/34] Scripts: palette handlers that update() runs play their palette's actions - A handler that a palette's update() runs in a later run of the same engine plays the actions of the run that showed the palette, as a handler's own run does. After the handler ends, or throws out of update(), app.doScript plays the run's own actions again. - script_palette_start gives the app the error of an open edit that cannot be settled, and the waiting events keep waiting; it no longer returns None, which showed nothing. - A palette event runs no handler or listener once a getter or an earlier listener took its control out of the palette, and a click or change is dropped when a getter read for the event disabled or hid the control or a container above it. - A palette list's change ends its run with an error when an item's text comes from a getter, an inherited property or an object. - The run's report of unhandled rejections is made again after the palettes are refreshed, leaving out a rejection that a getter gave a handler, and stays empty after a failed run. - A text a palette's field gave stays in the field until no change of that field waits, also while a run before the change set the field to the same text. - The report test replaces a waiting change ahead of another field's change, and the modal-wait test requires that no later frame is asked for. - docs/mcp.md: a list's change made before the app puts it in line is dropped without an error; an error a handler throws out of update() can be caught, and the run then keeps the handler's changes. --- crates/engine/src/script/actions.rs | 11 ++- crates/engine/src/script/mod.rs | 5 ++ crates/engine/src/script/palettes.rs | 17 ++-- crates/engine/src/script/scriptui.rs | 14 ++- crates/engine/src/tests/script_palettes.rs | 83 +++++++++++++++-- crates/js/src/builtins/promise.rs | 7 +- crates/js/src/realm.rs | 17 ++-- crates/js/src/scriptui.rs | 69 ++++++++++++--- crates/js/src/scriptui_tests.rs | 98 +++++++++++++++++++++ crates/ui-egui/src/script_palettes.rs | 9 +- crates/ui-egui/src/tests/script_palettes.rs | 49 +++++++++-- docs/mcp.md | 13 +-- 12 files changed, 331 insertions(+), 61 deletions(-) diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 2abb290cf7..e4767875a1 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -222,13 +222,18 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { if !matches!(arg(a, 3), Data::Undefined | Data::Bool(_)) { return Err(HostError::Type("doScript's dialogs must be true or false".into())); } - let found: Vec<&Playable> = h.actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect(); + // A palette's handler that a palette's `update()` runs plays the actions of the run that showed + // the palette, as the handler's own run would. + let handler = h.palette_actions.borrow(); + let actions = handler.as_deref().unwrap_or(&h.actions); + let found: Vec<&Playable> = actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect(); let p = match found.as_slice() { - [p] => *p, - [] if !h.actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))), + [p] => (*p).clone(), + [] if !actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))), [] => return Err(HostError::Error(format!("the set “{}” has no action “{}”", shown(set), shown(action)))), _ => return Err(HostError::Error(format!("the set “{}” has more than one action “{}”", shown(set), shown(action)))), }; + drop(handler); if p.steps.is_empty() { return Err(HostError::Error(format!("the action “{}” has no included steps", shown(&p.name)))); } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 5dd4472ed9..4fb5cd8617 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -842,6 +842,10 @@ struct Host { dom: dom::State, /// The actions `app.doScript` can play. actions: Vec, + /// While a palette's `update()` gives a waiting event to its palette, the actions of the run + /// that showed that palette, which `app.doScript` plays in place of [`Host::actions`]. A + /// palette's `paletteTake` sets them and its `palettePending` clears them. + palette_actions: RefCell>>, /// The index of each open document's active artboard as the run starts, by document uid. The /// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it. active_artboards: Vec<(u64, usize)>, @@ -2417,6 +2421,7 @@ impl Session { palette_event: RefCell::new(palette_event), dom: dom::State::new(heap_bytes), actions: request.actions, + palette_actions: RefCell::new(None), active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(), artboard_picks, run_docs: RefCell::new( diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 9e5c5d1ca2..a796df58e4 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -275,13 +275,15 @@ impl Palettes { } /// The oldest waiting event for a palette of the engine `engine`, which a palette's `update()` - /// in a run of that engine takes and hands to the palette at once ([`Palettes::next_of`]). - pub(crate) fn take_for(&mut self, engine: &str) -> Option { + /// in a run of that engine takes and hands to the palette at once ([`Palettes::next_of`]), with + /// the actions its handlers play: those of the run that first showed its palette. + pub(crate) fn take_for(&mut self, engine: &str) -> Option<(Queued, Vec)> { let q = self.next_of(engine).map(|(_, q)| q)?; if let Some(taken) = self.taken_inline.as_mut() { taken.push(q.ticket); } - Some(q) + let actions = self.actions.iter().find(|(id, _)| *id == q.palette).map(|(_, a)| a.clone()).unwrap_or_default(); + Some((q, actions)) } /// Whether an event waits for a palette of the engine `engine`, which [`Palettes::take_for`] @@ -450,12 +452,15 @@ impl Session { /// Starts the run of the oldest waiting palette event, when no run is going. → `None` when a /// run is going or no event waits; otherwise the run's name, or the error that ended it before - /// it began. + /// it began. An open edit that cannot be settled gives its error, and the events keep waiting. pub fn script_palette_start(&mut self) -> Option> { - // An event waits while a drag or an undo group is open, which a run cannot start in. - if self.script_running() || self.script_palettes.waiting.is_empty() || self.settle_for_script().is_err() { + if self.script_running() || self.script_palettes.waiting.is_empty() { return None; } + // An event waits while a drag or an undo group is open, which a run cannot start in. + if let Err(e) = self.settle_for_script() { + return Some(Err(e)); + } let (palette, mut queued) = self.script_palettes.next()?; self.script_palettes.started_ticket = Some(queued.ticket); queued.grants = Some(palette.grants.clone()); diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index 522a0e99d8..04216386bc 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -790,16 +790,24 @@ fn palette_draw(host: &Host, _: &[Data]) -> Result { } /// A palette's `update()` takes the oldest event the person gave a palette of the run's engine, -/// which no run has handled yet, as `paletteEvent` gives it; `null` when none waits. +/// which no run has handled yet, as `paletteEvent` gives it; `null` when none waits. Until the next +/// `palettePending`, `app.doScript` plays the actions of the run that showed the event's palette. fn palette_take(host: &Host, _: &[Data]) -> Result { let engine = palette_engine(host)?.to_string(); let taken = host.session.borrow_mut().script_palettes.take_for(&engine); - Ok(taken.map_or(Data::Null, event_data)) + let (data, actions) = match taken { + Some((queued, actions)) => (event_data(queued), Some(actions)), + None => (Data::Null, None), + }; + *host.palette_actions.borrow_mut() = actions; + Ok(data) } /// Whether an event waits for a palette of the run's engine, which a palette's `update()` asks -/// before it gives the palettes' controls and takes the event with `paletteTake`. +/// before it gives the palettes' controls and takes the event with `paletteTake`, and once more +/// after the event's handlers end. `app.doScript` then plays the run's own actions again. fn palette_pending(host: &Host, _: &[Data]) -> Result { + *host.palette_actions.borrow_mut() = None; let engine = palette_engine(host)?.to_string(); Ok(Data::Bool(host.session.borrow().script_palettes.waits_for(&engine))) } diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index f001f281d8..77d653c162 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -658,6 +658,66 @@ fn with_nobody_to_ask_an_event_whose_open_edit_cannot_be_settled_ends_with_that_ assert_eq!(clicked["log"], json!(["click 1"]), "only the click given after it ran"); } +#[test] +fn a_waiting_event_whose_open_edit_cannot_be_settled_gives_the_app_that_error_and_keeps_waiting() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + SETTLE_FAILS.with(|f| f.set(true)); + let started = s.script_palette_start(); + SETTLE_FAILS.with(|f| f.set(false)); + let e = started.expect("the start gives the app its error").unwrap_err().to_string(); + assert!(e.contains("could not be settled"), "{e}"); + assert_eq!(s.script_palette_events_waiting(), 1, "the click waits for a later start"); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); +} + +/// A palette in the engine `acts` whose button plays the action `Box` of the set `Set`, shown by +/// a run given that action, which draws a rectangle; and how many objects the document holds. +fn acts_palette(s: &mut Session, handler: &str) -> (u64, fn(&Session) -> usize) { + let actions = + json!([{"set": "Set", "name": "Box", "steps": [{"command": "shape.rectangle", "params": {"x": 40, "y": 0, "width": 5, "height": 5}}]}]); + let source = format!( + "#targetengine acts\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); b.onClick = function () {{ {handler} }}; p.show();" + ); + s.execute("script.run", &json!({"source": source, "name": "p.js", "actions": actions})).unwrap(); + fn objects(s: &Session) -> usize { + s.documents()[0].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() + } + (only_palette(s), objects) +} + +#[test] +fn a_handler_that_update_runs_plays_the_actions_of_the_run_that_showed_its_palette() { + let mut s = one_doc(); + let (id, objects) = acts_palette(&mut s, "app.doScript('Box', 'Set'); vc.log('played');"); + let before = objects(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + // A later run of the engine, given no actions, takes the click in its update(). + let log = run(&mut s, "#targetengine acts\np.update(); try { app.doScript('Box', 'Set'); } catch (e) { vc.log(e.message); }").unwrap()["log"] + .clone(); + assert_eq!(log, json!(["played", "there is no action set “Set”"]), "the run's own call plays the run's own actions"); + assert_eq!(objects(&s), before + 1, "the handler's action drew its rectangle"); +} + +#[test] +fn after_a_handler_that_update_runs_throws_the_run_plays_its_own_actions() { + let mut s = one_doc(); + let (id, objects) = acts_palette(&mut s, "throw new Error('broken');"); + let before = objects(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + let log = run( + &mut s, + "#targetengine acts\ntry { p.update(); } catch (e) { vc.log(e.message); } \ + try { app.doScript('Box', 'Set'); } catch (e) { vc.log(e.message); }", + ) + .unwrap()["log"] + .clone(); + assert_eq!(log, json!(["broken", "there is no action set “Set”"])); + assert_eq!(objects(&s), before); +} + #[test] fn a_handler_plays_the_actions_of_the_run_that_showed_its_palette() { let mut s = one_doc(); @@ -709,14 +769,23 @@ fn a_point_change_a_palette_getter_makes_after_the_run_is_kept() { #[test] fn with_nobody_to_ask_an_event_that_replaces_a_waiting_one_answers_with_its_own_report() { let mut s = one_doc(); - run(&mut s, TOOLS).unwrap(); + run( + &mut s, + "#targetengine fields\nvar p = new Window('palette'); var one = p.add('edittext', undefined, ''); \ + var two = p.add('edittext', undefined, ''); one.onChange = function () { vc.log('change ' + one.text); }; \ + two.onChange = function () { vc.log('other ' + two.text); }; p.show();", + ) + .unwrap(); let id = only_palette(&s); - assert_eq!(s.script_palette_event(id, UiEvent::Change(2, crate::script::UiValue::Text("a".into()))), Ok(Waiting::Added)); - assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); - // The new change takes the waiting change's place, before the click. - let changed = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 2, "value": "z"})).unwrap(); - assert_eq!(changed["log"], json!(["change z"])); - assert_eq!(s.script_palette_events_waiting(), 0, "the click after it ran too"); + let text = |c: usize, t: &str| UiEvent::Change(c, crate::script::UiValue::Text(t.into())); + assert_eq!(s.script_palette_event(id, text(1, "a")), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, text(2, "q")), Ok(Waiting::Added)); + // The new change takes the place of the first field's change, ahead of the second field's. + let changed = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 1, "value": "z"})).unwrap(); + assert_eq!(changed["log"], json!(["change z"]), "the report is the given change's, not the last run's"); + assert_eq!(s.script_palette_events_waiting(), 0, "the second field's change ran too"); + let texts = run(&mut s, "#targetengine fields\nvc.log(one.text + ' ' + two.text);").unwrap()["log"].clone(); + assert_eq!(texts, json!(["z q"])); } #[test] diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 54e5eda498..5136b9299e 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -741,9 +741,10 @@ impl Interp { } /// The promises the run rejected that still have no handler, the first [`MAX_REPORTED`] of - /// them described, and how many there are; the run's notes are cleared. - pub(crate) fn take_unhandled(&mut self) -> (Vec, usize) { - let rejected = std::mem::take(&mut self.promises.rejected); + /// them described, and how many there are. The run's notes stay until the next run starts, so a + /// later call leaves out a promise that has a handler since. + pub(crate) fn unhandled(&mut self) -> (Vec, usize) { + let rejected = self.promises.rejected.clone(); let mut out = Vec::new(); let mut attribution = Vec::new(); let mut count = 0; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index b31c123bf2..ee259f5eb3 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -450,7 +450,7 @@ impl Realm { } match result { Ok(v) => { - self.rejections = interp.take_unhandled(); + self.rejections = interp.unhandled(); Ok(interp.to_js_value(&v)) } Err(Abrupt::Throw(v)) => { @@ -720,8 +720,10 @@ impl Realm { /// the run that just ended left them; nothing when it keeps none. A getter it reads runs in the /// run's fuel, at most [`Realm::set_unbroken_fuel`] of it, as a nested run that cannot pause /// does; what it throws ends the run. The promise jobs a getter queues run in the same fuel, - /// and the host then gets the controls once more ([`crate::scriptui::refresh`]). Their - /// unhandled rejections join the run's ([`Realm::unhandled_rejections`]). + /// and the host then gets the controls once more ([`crate::scriptui::refresh`]). The run's + /// report of unhandled rejections ([`Realm::unhandled_rejections`]) is then made again: it + /// takes in the rejections of those jobs and leaves out a run's rejection that a getter or a + /// job gave a handler. pub fn refresh_script_ui(&mut self) -> Result<(), RunError> { let interp = &mut self.interp; let total = interp.fuel; @@ -732,10 +734,7 @@ impl Realm { interp.fuel = total - used; match r { Ok(()) => { - let (more, count) = self.interp.take_unhandled(); - let room = crate::builtins::promise::MAX_REPORTED.saturating_sub(self.rejections.0.len()); - self.rejections.0.extend(more.into_iter().take(room)); - self.rejections.1 += count; + self.rejections = self.interp.unhandled(); Ok(()) } Err(Abrupt::Limit(LimitKind::Fuel)) if total > cap => self.outcome(Err(Abrupt::Limit(LimitKind::Unbroken))).map(drop), @@ -745,14 +744,16 @@ impl Realm { /// [`Realm::refresh_script_ui`] after a run that failed: what the refresh throws is dropped, /// and the run's error keeps its place ([`Realm::error_source`], [`Realm::error_mark`]) and - /// its thrown value. + /// its thrown value. The report of unhandled rejections stays empty, as after any failed run. pub fn refresh_script_ui_after_error(&mut self) { let (tag, mark) = (self.interp.error_tag, self.interp.error_mark); let thrown = self.interp.last_thrown.clone(); + let rejections = std::mem::take(&mut self.rejections); let _ = self.refresh_script_ui(); self.interp.error_tag = tag; self.interp.error_mark = mark; self.interp.last_thrown = thrown; + self.rejections = rejections; } /// Adds the global constructors `File` and `Folder`, whose file system work the host functions diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 0833989a6f..808dd83327 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -68,7 +68,8 @@ //! `update()` on a shown palette, or on a `group` or a `panel` in one, takes each event that waits //! for a palette of the run's engine from the host's `paletteTake` (as `paletteEvent` gives it, or //! `null`) and gives it to its palette, while the host's `palettePending` says one waits, giving -//! `paletteUpdate` each palette's description before each one. Then, called from the script's own code (not from a +//! `paletteUpdate` each palette's description before each one. When a handler's exception ends +//! this, `update()` calls `palettePending` once more before the exception leaves it. Then, called from the script's own code (not from a //! handler, a callback of a built-in function, a getter or a conversion), it asks the host's //! `paletteDraw` whether the palette is drawn now, and when it is, gives `paletteUpdate` the //! palette's description. On the showing dialog, or a group or panel in it, `update()` does @@ -1257,20 +1258,23 @@ fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult Ok(dispatch_for(i, target, ty, callback, None)?.unwrap_or(false)) } -/// The palette and the event it takes, whose handlers run only while the palette takes the event -/// ([`still_takes`]); `None` for a dialog, which always takes it. -type Taker = Option<(ObjId, ObjId)>; +/// The palette, the event it takes and the event's control, whose handlers run only while the +/// palette takes the event ([`still_takes`]) and holds the control; `None` for a dialog, which +/// always takes it. +type Taker = Option<(ObjId, ObjId, ObjId)>; -/// Does the palette of `taker` still take its event? Always true for a dialog. +/// Does the palette of `taker` still take its event and hold its control? Always true for a +/// dialog. fn takes(i: &mut Interp, taker: Taker) -> JsResult { match taker { - Some((win, ev)) => still_takes(i, win, ev, None), + Some((win, ev, c)) => Ok(still_takes(i, win, ev, None)? && holds(i, win, c)?), None => Ok(true), } } /// [`dispatch`] for the event a palette takes (`taker`): no handler or listener runs once a getter, -/// a handler or a listener of the event closed the palette. → `None` when that happened. +/// a handler or a listener of the event closed the palette or took the event's control out of it. +/// → `None` when that happened. fn dispatch_for(i: &mut Interp, target: ObjId, ty: &str, callback: &str, taker: Taker) -> JsResult> { let above = containers_above(i, target)?; let proto = classes(i)?.event_proto; @@ -1723,7 +1727,15 @@ fn take_each(i: &mut Interp) -> JsResult<()> { if answer.as_object().is_none() { return Ok(()); } - deliver(i, answer)?; + if let Err(e) = deliver(i, answer) { + // The host learns that the event's handlers have ended, as it does before the next + // event, when a handler's exception ends the loop. + if let Abrupt::Throw(v) = &e { + let v = v.clone(); + let _ = i.rooted(std::slice::from_ref(&v), |i| i.call(&pending, &Value::Undefined, &[])); + } + return Err(e); + } } } @@ -1887,11 +1899,12 @@ fn deliver(i: &mut Interp, answer: Value) -> JsResult { if event == "close" { close_palette(i, win)?; } else { - let (_, nodes, ..) = describe(i, win)?; + let (desc, nodes, ..) = describe(i, win)?; // A getter read in the description may have closed the palette. if !still_takes(i, win, ev, None)? { return Ok(Value::Undefined); } + i.temp_roots.push(desc.clone()); i.temp_roots.push(Value::Object(nodes)); let held = list_values(i, nodes)?; // The host gives the control's id, which is found again in the palette as it is now: a @@ -1926,6 +1939,11 @@ fn deliver(i: &mut Interp, answer: Value) -> JsResult { let Some(at) = at.filter(|_| !gone) else { return Err(error(i, "a palette event names a control the palette no longer holds")); }; + // A getter read in the description may have disabled or hidden the control, or a + // container above it: the event is dropped, as the host drops one for such a control. + if !live_in(i, &desc, at)? { + return Ok(Value::Undefined); + } set_slot(i, ev, "id", Value::Number(at as f64))?; take_event(i, win, nodes, ev, &event, None)?; } @@ -1935,6 +1953,27 @@ fn deliver(i: &mut Interp, answer: Value) -> JsResult { r } +/// Whether the element at `at` in the description `desc` ([`describe`]) is enabled and visible, and +/// every container above it too. +fn live_in(i: &Interp, desc: &Value, at: usize) -> JsResult { + let Some(d) = desc.as_object() else { return Ok(false) }; + let Some(nodes) = slot(i, d, "nodes")?.as_object() else { return Ok(false) }; + let nodes = list_values(i, nodes)?; + let mut n = Some(at); + for _ in 0..=nodes.len() { + let Some(k) = n else { return Ok(true) }; + let Some(node) = nodes.get(k).and_then(Value::as_object) else { return Ok(false) }; + if !slot(i, node, "enabled")?.truthy() || !slot(i, node, "visible")?.truthy() { + return Ok(false); + } + n = match slot(i, node, "parent")? { + Value::Number(p) if p >= 0.0 && p < k as f64 => Some(p as usize), + _ => None, + }; + } + Ok(false) +} + /// Whether the window `win` still takes the event `ev`: a dialog (`keep` is `Some`) always does, /// and a palette only while the host shows it under the id the event names. A getter or a handler /// run for the event may have closed or hidden the palette. @@ -2123,7 +2162,8 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { /// dialog's button without `onClick` and without a `click` listener of its own asks to close it /// with 1 when it is the default element and 2 when it is the cancel element, which `keep` /// (`show()`'s kept values) names; a palette has no `keep`. No handler or listener of a palette -/// runs once a getter, a setter or an earlier handler of the event closed the palette. +/// runs once a getter, a setter or an earlier handler of the event closed the palette or took the +/// control out of it. fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, keep: Option<&[Value]>) -> JsResult<()> { let id = match slot(i, ev, "id")? { Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => n as usize, @@ -2134,7 +2174,7 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, 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")?; - let taker = if keep.is_none() { Some((win, ev)) } else { None }; + let taker = if keep.is_none() { Some((win, ev, c)) } else { None }; match event { "click" => { let Some(handled) = click_control_for(i, c, &kind, taker)? else { @@ -2221,7 +2261,7 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, /// Does the list `c` hold items with the texts in `seen` (an array of strings), in that order? True /// when `seen` is not an array. A text a later item's getter changes after it was compared counts -/// as a change. +/// as a change, and so does a text that is not a plain value of the item's own. fn same_items(i: &mut Interp, c: ObjId, seen: &Value) -> JsResult { let Some(seen) = seen.as_object() else { return Ok(true) }; let seen = list_values(i, seen)?; @@ -2240,11 +2280,12 @@ fn same_items(i: &mut Interp, c: ObjId, seen: &Value) -> JsResult { } texts.push((item, text)); } - // Read again without running getters: only a text held as a plain value can be checked so. + // Read again without running getters. Only a text held as a plain value can be checked so: + // one a getter, an inherited property or an object gives cannot, and counts as a change. for (item, text) in texts { let now = match i.get_own_property(item, &key("text"))? { Some(Prop::Data { value, .. }) if !matches!(value, Value::Object(_)) => value, - _ => continue, + _ => return Ok(false), }; if i.to_str(&now)?.to_rust_string() != text { return Ok(false); diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 2b8548c200..72ec393c9f 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -813,6 +813,73 @@ fn a_palette_s_show_returns_at_once_and_its_events_run_its_handlers() { assert_eq!(r.run("Window.__vcPaletteEvent(); 'nothing'").unwrap(), JsValue::String("nothing".into()), "no event left: nothing runs"); } +#[test] +fn a_palette_click_runs_no_handler_once_its_button_was_taken_out_of_the_palette() { + // The button's onClick getter takes it out of the palette and gives a function. + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var log = []; \ + Object.defineProperty(b, 'onClick', {get: function () { p.remove(b); return function () { log.push('ran'); }; }}); p.show();", + ) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()), "the getter's function does not run"); + // A capturing listener on the palette takes the button out before the button's own turn. + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var log = []; \ + b.onClick = function () { log.push('click'); }; b.addEventListener('click', function () { log.push('listener'); }); \ + p.addEventListener('click', function () { log.push('capture'); p.remove(b); }, true); p.show();", + ) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("capture".into())); +} + +#[test] +fn a_palette_click_is_dropped_when_a_getter_read_for_it_disables_its_button_or_a_group_above() { + for disable in ["b.enabled = false;", "g.enabled = false;", "g.visible = false;"] { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(3))]); + r.run(&format!( + "var armed = false, log = []; var p = new Window('palette'); var label = p.add('statictext', undefined, 'L'); \ + var g = p.add('group'); var b = g.add('button', undefined, 'Go'); b.onClick = function () {{ log.push('click'); }}; \ + Object.defineProperty(label, 'text', {{get: function () {{ if (armed) {{ armed = false; {disable} }} return 'L'; }}}}); \ + p.show(); armed = true;" + )) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()), "{disable}"); + } +} + +#[test] +fn a_palette_list_change_throws_when_an_item_s_text_comes_from_a_getter() { + let (mut r, _) = palette_realm(vec![seen_list_change(0.0), seen_list_change(0.0)]); + // The first item's getter gives `label`, which the second item's getter changes after the + // first was compared. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; var label = 'a', armed = false; \ + l.onChange = function () { got.push(String(l.selection)); }; \ + Object.defineProperty(l.items[0], 'text', {get: function () { return label; }}); \ + Object.defineProperty(l.items[1], 'text', {get: function () { if (armed) { label = 'z'; } return 'b'; }}); \ + p.show();", + ) + .unwrap(); + for arm in ["false", "true"] { + let e = r.run(&format!("armed = {arm}; label = 'a'; try {{ Window.__vcPaletteEvent(); 'none'; }} catch (e) {{ e.message; }}")).unwrap(); + assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into()), "armed {arm}"); + } + assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into())); +} + +#[test] +fn update_asks_the_host_once_more_after_a_handler_s_exception() { + let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new()); + r.run("var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); b.onClick = function () { throw new Error('broken'); }; p.show();") + .unwrap(); + let thrown = r.run("try { p.update(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(thrown, JsValue::String("broken".into())); + let asked: Vec = names(&calls).into_iter().filter(|n| n == "palettePending" || n == "paletteTake").collect(); + assert_eq!(asked, ["palettePending", "paletteTake", "palettePending"], "the host learns the event's handlers ended"); +} + #[test] fn closing_a_palette_runs_on_close_which_can_keep_it_open() { let (mut r, calls) = palette_realm(vec![palette_event(1.0, close()), palette_event(1.0, close()), palette_event(1.0, click(1))]); @@ -1197,6 +1264,37 @@ fn promise_jobs_a_palette_getter_queues_while_the_palette_is_refreshed_run() { assert_eq!(r.run("[ran, b.text].join()").unwrap(), JsValue::String("1,Done".into()), "the job the getter queued ran with the refresh"); } +#[test] +fn a_run_s_rejection_that_a_palette_getter_handles_during_the_refresh_is_not_reported() { + let (mut r, _) = palette_realm(Vec::new()); + r.add_es2015(); + r.run( + "var armed = false, caught = 0; var p = new Window('palette'); p.add('button', undefined, 'Go'); \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; \ + early.catch(function () { caught++; }); } return 'P'; }}); \ + p.show(); var early = Promise.reject(new Error('early')); armed = true;", + ) + .unwrap(); + assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (1, 1), "the run left the rejection unhandled"); + r.refresh_script_ui().unwrap(); + assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (0, 0), "the getter gave it a handler"); +} + +#[test] +fn a_rejection_a_palette_getter_makes_while_a_failed_run_is_refreshed_is_not_reported() { + let (mut r, _) = palette_realm(Vec::new()); + r.add_es2015(); + r.run( + "var armed = false; var p = new Window('palette'); p.add('button', undefined, 'Go'); \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; \ + Promise.reject('late'); } return 'P'; }}); p.show();", + ) + .unwrap(); + assert!(r.run("armed = true; throw new Error('failed');").is_err()); + r.refresh_script_ui_after_error(); + assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (0, 0), "a failed run reports no rejection"); +} + #[test] fn promise_jobs_a_palette_getter_queues_on_every_refresh_run_without_another_refresh() { let (mut r, calls) = palette_realm(Vec::new()); diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index 40754bc554..2cc1d81340 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -47,7 +47,8 @@ pub(crate) struct PaletteWindow { /// the app takes them leaves each with its own control. given: Vec<(ScopeHandle, ScopeHandle, Vec)>, /// The text each edit field gave the script, by the field's id, while its change waits: the - /// field shows it until the palette's field holds it or no event waits. + /// field shows it until no change of that field waits, even while the palette's field holds the + /// same text, since a run before the change may set the field to another one. pending: BTreeMap, open: bool, } @@ -58,13 +59,13 @@ impl PaletteWindow { } /// The palette as the session has it now. A typed text whose field the palette no longer has is - /// dropped, and so is a given text once the field holds it, or once its change no longer waits - /// in the session (`waiting`: [`vectorcraft_engine::Session::script_palette_changes_waiting`]). + /// dropped, and so is a given text once its change no longer waits in the session (`waiting`: + /// [`vectorcraft_engine::Session::script_palette_changes_waiting`]). fn sync(&mut self, palette: ScriptPalette, waiting: &[(u64, u64)]) { self.palette = palette; script_window::keep_fields(&self.palette.dialog, &mut self.drafts); let (nodes, palette, given) = (&self.palette.dialog.nodes, self.palette.id, !self.given.is_empty()); - self.pending.retain(|id, text| (given || waiting.contains(&(palette, *id))) && nodes.iter().any(|n| n.id == *id && n.text != *text)); + self.pending.retain(|id, _| (given || waiting.contains(&(palette, *id))) && nodes.iter().any(|n| n.id == *id)); } /// Draws the palette's controls in `ui` and takes what the person did, as its body does. diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 52c143ff61..4b72675b2e 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -595,10 +595,23 @@ fn a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() { give(&app, id, UiEvent::Click(1)); follow(&mut app); assert_eq!(app.session.script_palette_events_waiting(), 1); - assert!(settle(&mut app, |app, ctx| app.tick(ctx)), "the waiting click asks for no frames while the run waits for its answer"); + let delay = settled_delay(&mut app); + assert_eq!(delay, std::time::Duration::MAX, "the waiting click asks for no frames, now or later, while the run waits for its answer"); assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits"); } +/// Runs the app's ticks until one asks for no later frame, at most five. → the last one's delay. +fn settled_delay(app: &mut VectorcraftApp) -> std::time::Duration { + let mut delay = std::time::Duration::ZERO; + for _ in 0..5 { + delay = frame_delay(app, |app, ctx| app.tick(ctx)); + if delay == std::time::Duration::MAX { + break; + } + } + delay +} + #[test] fn a_click_waiting_for_an_open_undo_group_asks_for_no_frames_and_runs_after_it() { let mut app = app(); @@ -607,13 +620,7 @@ fn a_click_waiting_for_an_open_undo_group_asks_for_no_frames_and_runs_after_it() give(&app, id, UiEvent::Click(1)); follow(&mut app); assert_eq!(app.session.script_palette_events_waiting(), 1); - let mut delay = std::time::Duration::ZERO; - for _ in 0..5 { - delay = frame_delay(&mut app, |app, ctx| app.tick(ctx)); - if delay == std::time::Duration::MAX { - break; - } - } + let delay = settled_delay(&mut app); assert_eq!(delay, std::time::Duration::MAX, "the waiting click asks for no frames, now or later, while the undo group is open"); assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits"); app.run("edit.undoGroup.end", json!({})).unwrap(); @@ -647,6 +654,32 @@ fn a_given_text_stays_in_its_field_while_its_change_waits_for_a_run() { assert_eq!(shown(&app).as_deref(), Some("new"), "the field holds the text the script took"); } +#[test] +fn a_given_text_stays_in_its_field_while_its_change_waits_after_a_run_set_the_field_to_it() { + let mut app = app(); + let source = "#targetengine fields\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'old'); \ + t.onChange = function () { vc.log('change ' + t.text); }; p.show();"; + let id = shown(&mut app, source); + start(&mut app, "while (true) {}"); + script_runs::poll(&mut app); + with_palette(&app, id, |w| w.commit_text(1, "A")).unwrap(); + follow(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 1, "the change waits for the run"); + assert!(app.session.script_abandon()); + let shown = |app: &VectorcraftApp| with_palette(app, id, |w| w.shown_text(1)).flatten(); + // Runs before the change's set the field to the given text, then to another one. + for text in ["A", "B"] { + start(&mut app, &format!("#targetengine fields\nt.text = '{text}';")); + run_to_end(&mut app); + follow(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 1, "the change still waits after the run that set {text}"); + assert_eq!(shown(&app).as_deref(), Some("A"), "the field keeps the given text after the run that set {text}"); + } + assert!(script_palettes::start_next(&mut app)); + run_to_end(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["change A"])); +} + #[test] fn a_typed_text_a_click_gives_stays_in_its_field_while_its_change_waits_for_a_run() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 439f96e561..1d86455f9c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4090,11 +4090,14 @@ the same controls, handlers and limits: or close waits under what its scope and all the texts it commits allow. A text edited in several scopes goes under what all of them allow. A waiting click or change, and a text typed in a field, stay with their control when a run adds controls before it. A waiting event whose control is gone, or that its control can no longer take - because a handler disabled or hid it, is dropped. A list's change ends its run - with an error when a script added or removed the list's items after the person chose, even if the list again - holds the same texts. A text typed in a palette's field that is longer than 16 KiB stays in the field with the error in the status bar, and a click or close waits - until it is fixed. An error in a handler ends that run like any failed run, puts the documents back, and - leaves the palette open. In the app, `alert`, `confirm`, `prompt` and a dialog's `show()` throw inside a + because a handler disabled or hid it, is dropped. A list's change is dropped, with no error and no handler run, + when a script added or removed the list's items after the person chose and before the app put the change in + line. Once the change waits in line, it ends its run with an error when a script added or removed the list's + items, even if the list again holds the same texts, and when an item's text comes from a getter rather than a + plain value. A text typed in a palette's field that is longer than 16 KiB stays in the field with the error in the status bar, and a click or close waits + until it is fixed. An error in a handler that ends its run fails that run like any failed run, puts the + documents back, and leaves the palette open. A handler that a palette's `update()` runs throws its error from + that `update()` call: when the script catches it, the run goes on and keeps the handler's changes. In the app, `alert`, `confirm`, `prompt` and a dialog's `show()` throw inside a handler; with nobody to ask, a handler's run has no `answers` and ends at the first of them. - A session keeps at most 16 palettes, shown or hidden, past which `show()` throws a `RangeError`, and at most 64 waiting events, past which an event is refused. Hiding or closing a palette drops its waiting events. These From 49af2bf194e464e93e66bcb3e19e913e68bdb840 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 22:44:40 -0800 Subject: [PATCH 24/34] Scripts: format the new palette tests --- crates/engine/src/tests/script_palettes.rs | 4 ++-- crates/js/src/scriptui_tests.rs | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 77d653c162..a522a0468f 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -695,8 +695,8 @@ fn a_handler_that_update_runs_plays_the_actions_of_the_run_that_showed_its_palet let before = objects(&s); assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); // A later run of the engine, given no actions, takes the click in its update(). - let log = run(&mut s, "#targetengine acts\np.update(); try { app.doScript('Box', 'Set'); } catch (e) { vc.log(e.message); }").unwrap()["log"] - .clone(); + let log = + run(&mut s, "#targetengine acts\np.update(); try { app.doScript('Box', 'Set'); } catch (e) { vc.log(e.message); }").unwrap()["log"].clone(); assert_eq!(log, json!(["played", "there is no action set “Set”"]), "the run's own call plays the run's own actions"); assert_eq!(objects(&s), before + 1, "the handler's action drew its rectangle"); } diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 72ec393c9f..edd5c1121a 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -872,8 +872,10 @@ fn a_palette_list_change_throws_when_an_item_s_text_comes_from_a_getter() { #[test] fn update_asks_the_host_once_more_after_a_handler_s_exception() { let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new()); - r.run("var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); b.onClick = function () { throw new Error('broken'); }; p.show();") - .unwrap(); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); b.onClick = function () { throw new Error('broken'); }; p.show();", + ) + .unwrap(); let thrown = r.run("try { p.update(); 'none'; } catch (e) { e.message; }").unwrap(); assert_eq!(thrown, JsValue::String("broken".into())); let asked: Vec = names(&calls).into_iter().filter(|n| n == "palettePending" || n == "paletteTake").collect(); From 666f7e3db2226c55893bb431b8503a90fd4505ed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 01:54:08 -0800 Subject: [PATCH 25/34] Scripts: a palette click is dropped when a later getter disables its button A getter read after a button while the palette was described could disable or hide the button, or a group above it, after the description recorded it as enabled, and the click still ran its handler. - Palette states are read without running a getter, once every description getter (the default and cancel elements included) has run, and a state that a getter gives counts as off. Dialogs keep reading the states through their getters. - Delivering a palette event reads the states of the control and the groups above it again the same way, and checks that the palette still holds the control, before the handler runs. - docs/mcp.md, the progress line and script.palette.event's params text describe the rule. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/js/src/scriptui.rs | 101 ++++++++++++++++++++++++++++--- crates/js/src/scriptui_tests.rs | 33 ++++++++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 5 files changed, 129 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index a55af85287..273d49763c 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Script Palette Event", [], None, - "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error", + "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler", always, palette_event ), diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 808dd83327..0657e9ccad 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -1944,6 +1944,12 @@ fn deliver(i: &mut Interp, answer: Value) -> JsResult { if !live_in(i, &desc, at)? { return Ok(Value::Undefined); } + // A getter read later in the description may have disabled or hidden the control or a + // container above it after the description recorded it: read the states again without + // running a getter, and drop the event unless they are all live. + if !live_now(i, &desc, &held, at)? || !still_takes(i, win, ev, None)? || !holds_value(i, win, &held, at)? { + return Ok(Value::Undefined); + } set_slot(i, ev, "id", Value::Number(at as f64))?; take_event(i, win, nodes, ev, &event, None)?; } @@ -1974,6 +1980,47 @@ fn live_in(i: &Interp, desc: &Value, at: usize) -> JsResult { Ok(false) } +/// Whether the control at `at` in `held` (the description's controls, in its order) and every +/// container above it, by the parents in `desc`, are enabled and visible as they are now, read +/// without running a getter ([`plain_state`]). +fn live_now(i: &Interp, desc: &Value, held: &[Value], at: usize) -> JsResult { + let Some(d) = desc.as_object() else { return Ok(false) }; + let Some(nodes) = slot(i, d, "nodes")?.as_object() else { return Ok(false) }; + let nodes = list_values(i, nodes)?; + let mut n = Some(at); + for _ in 0..=nodes.len() { + let Some(k) = n else { return Ok(true) }; + let (Some(node), Some(o)) = (nodes.get(k).and_then(Value::as_object), held.get(k).and_then(Value::as_object)) else { + return Ok(false); + }; + if !plain_state(i, o, "enabled")? || !plain_state(i, o, "visible")? { + return Ok(false); + } + n = match slot(i, node, "parent")? { + Value::Number(p) if p >= 0.0 && p < k as f64 => Some(p as usize), + _ => None, + }; + } + Ok(false) +} + +/// The state `name` of `o`, its own or the one its prototypes give, read without running a getter; +/// `false` when a getter gives it or nothing does. +fn plain_state(i: &Interp, o: ObjId, name: &str) -> JsResult { + Ok(match i.find_property(o, &key(name))? { + Some(Prop::Data { value, .. }) => value.truthy(), + _ => false, + }) +} + +/// Whether the palette `win` still holds the control at `at` in `held`. +fn holds_value(i: &mut Interp, win: ObjId, held: &[Value], at: usize) -> JsResult { + match held.get(at).and_then(Value::as_object) { + Some(c) => holds(i, win, c), + None => Ok(false), + } +} + /// Whether the window `win` still takes the event `ev`: a dialog (`keep` is `Some`) always does, /// and a palette only while the host shows it under the id the event names. A getter or a handler /// run for the event may have closed or hidden the palette. @@ -2476,6 +2523,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { stack.push((kid, index, depth + 1)); } } + let in_palette = order.first().is_some_and(|(_, kind, _)| kind == "palette"); 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()); @@ -2506,8 +2554,13 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { ("name".into(), Data::String(name.clone())), ("text".into(), Data::String(text.clone())), ]; - let enabled = get(i, o, "enabled")?.truthy(); - let visible = get(i, o, "visible")?.truthy(); + // In a palette, the states are read without running a getter, and a state that a getter + // gives counts as off, as when an event for the control is delivered ([`plain_state`]). + let (enabled, visible) = if in_palette { + (plain_state(i, o, "enabled")?, plain_state(i, o, "visible")?) + } else { + (get(i, o, "enabled")?.truthy(), get(i, o, "visible")?.truthy()) + }; // A control is enabled and visible only while every container above it is. let (above_enabled, above_visible) = if *parent >= 0.0 { live.get(*parent as usize).copied().unwrap_or((true, true)) } else { (true, true) }; live.push((enabled && above_enabled, visible && above_visible)); @@ -2605,19 +2658,47 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { snapshot.push(listed); selections.push(selected); } - let target = |i: &mut Interp, name: &str, word: &str| -> JsResult { - let given = get(i, win, name)?; - if let Some(n) = objects.iter().position(|o| same(o, &given)) { - return Ok(n as f64); + // The default and cancel elements are read before the states below, since their getters may + // also change a control's state. + let given_def = get(i, win, "defaultElement")?; + i.temp_roots.push(given_def.clone()); + let given_cancel = get(i, win, "cancelElement")?; + i.temp_roots.push(given_cancel.clone()); + // A palette's states are read again once every getter above has run, since one may have + // changed a control's state after it was read. + if in_palette { + let mut live: Vec<(bool, bool)> = Vec::with_capacity(order.len()); + for (n, (o, kind, parent)) in order.iter().enumerate() { + let (enabled, visible) = (plain_state(i, *o, "enabled")?, plain_state(i, *o, "visible")?); + let (above_enabled, above_visible) = + if *parent >= 0.0 { live.get(*parent as usize).copied().unwrap_or((true, true)) } else { (true, true) }; + live.push((enabled && above_enabled, visible && above_visible)); + if let Some(entry) = names.get_mut(n) { + entry.0 = kind == "button" && enabled && visible && above_enabled && above_visible; + } + if let Some(Data::Object(d)) = nodes.get_mut(n) { + for (field, value) in d.iter_mut() { + match field.as_str() { + "enabled" => *value = Data::Bool(enabled), + "visible" => *value = Data::Bool(visible), + _ => {} + } + } + } + } + } + let target = |given: &Value, word: &str| -> f64 { + if let Some(n) = objects.iter().position(|o| same(o, given)) { + return n as f64; } if !matches!(given, Value::Undefined | Value::Null) { - return Ok(-1.0); + return -1.0; } let button = |by_name: bool| names.iter().position(|(c, n, t)| *c && (if by_name { n } else { t }).to_lowercase() == word); - Ok(button(true).or_else(|| button(false)).map_or(-1.0, |n| n as f64)) + 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 def = target(&given_def, "ok"); + let cancel = target(&given_cancel, "cancel"); if !lists_unchanged(i, &order, &snapshot, &selections)? || !tree_unchanged(i, &order, &tree)? || !texts_unchanged(i, &item_texts)? { return Ok(None); } diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index edd5c1121a..7917d0241b 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -849,6 +849,39 @@ fn a_palette_click_is_dropped_when_a_getter_read_for_it_disables_its_button_or_a } } +#[test] +fn a_palette_click_is_dropped_when_a_getter_read_after_its_button_disables_the_button_or_a_group_above() { + for disable in ["b.enabled = false;", "g.enabled = false;", "g.visible = false;"] { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run(&format!( + "var armed = false, log = []; var p = new Window('palette'); \ + var g = p.add('group'); var b = g.add('button', undefined, 'Go'); b.onClick = function () {{ log.push('click'); }}; \ + var label = p.add('statictext', undefined, 'L'); \ + Object.defineProperty(label, 'text', {{get: function () {{ if (armed) {{ armed = false; {disable} }} return 'L'; }}}}); \ + p.show(); armed = true;" + )) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()), "{disable}"); + } + // A getter that gives the button's state, and disables it while it says the button is visible. + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run( + "var armed = false, log = []; var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); \ + b.onClick = function () { log.push('click'); }; p.add('statictext', undefined, 'L'); p.show(); \ + Object.defineProperty(b, 'visible', {get: function () { b.enabled = false; return true; }}); b.enabled = true;", + ) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into())); + // Without a getter that disables anything, the same click runs its handler. + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run( + "var log = []; var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); \ + b.onClick = function () { log.push('click'); }; p.add('statictext', undefined, 'L'); p.show();", + ) + .unwrap(); + assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("click".into())); +} + #[test] fn a_palette_list_change_throws_when_an_item_s_text_comes_from_a_getter() { let (mut r, _) = palette_realm(vec![seen_list_change(0.0), seen_list_change(0.0)]); diff --git a/docs/mcp.md b/docs/mcp.md index 4c791ef522..ab2b982704 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4090,7 +4090,9 @@ the same controls, handlers and limits: or close waits under what its scope and all the texts it commits allow. A text edited in several scopes goes under what all of them allow. A waiting click or change, and a text typed in a field, stay with their control when a run adds controls before it. A waiting event whose control is gone, or that its control can no longer take - because a handler disabled or hid it, is dropped. A list's change is dropped, with no error and no handler run, + because a handler, or a getter read while the palette is described for the event, disabled or hid it or a group + above it, is dropped. A palette's control or group whose `enabled` + or `visible` state a getter gives is shown disabled or hidden, and its events are dropped. A list's change is dropped, with no error and no handler run, when a script added or removed the list's items after the person chose and before the app put the change in line. Once the change waits in line, it ends its run with an error when a script added or removed the list's items, even if the list again holds the same texts, and when an item's text comes from a getter rather than a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7ead791d47..c96f136ba7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1178,7 +1178,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`). - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person and runs the controls' `onClick`, `onChanging` and `onChange` handlers. The window's own callbacks are `onShow`, which runs when `show()` starts, and `onClose`, which runs before the dialog closes and keeps it open when it returns false. `show()` returns the result of `close(result)`, or 1 for the default button and 2 for the cancel button when the button has no `onClick` or click listener and no handler closed the dialog with another result. Controls also take `notify`, size objects a script can set one side of, lists' `find` and `remove`, and `addEventListener` for clicks and changes, which the dialog also takes for `show`; `Window.alert`, `Window.confirm` and `Window.prompt` open the script dialogs; a run over MCP or the command line takes the clicks and changes from a `window` answer. `new Window` and `add` also build a window or a control and the controls inside it from a resource specification (https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/). Other control types throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`. - - Scripts: ScriptUI's `new Window("palette")` makes a palette in a script whose `#targetengine` names an engine other than `main`, and the palette's `show()` shows it beside the documents, where it stays open after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going. A newer change for the same control takes a waiting change's place only when no click or close of that palette waits after the waiting change, and a newer click or close takes a waiting one's place only when no change of that palette waits after it; in both cases the two must be given under the same file access scope. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes whose file access scopes cover the run's scope, so a Cancel button can stop a loop; an event given under narrower roots or another script gate waits for a run of its own instead. `update()` in the script's own code in the app also pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. `close()` and the close box close a palette unless its `onClose` returns `false`; the end of its engine or the session closes it too. A session keeps at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.rs`. + - Scripts: ScriptUI's `new Window("palette")` makes a palette in a script whose `#targetengine` names an engine other than `main`, and the palette's `show()` shows it beside the documents, where it stays open after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going. A click or change is dropped when its control, or a group above it, is disabled or hidden once the palette is described for the event, or when a getter gives that `enabled` or `visible` state. A newer change for the same control takes a waiting change's place only when no click or close of that palette waits after the waiting change, and a newer click or close takes a waiting one's place only when no change of that palette waits after it; in both cases the two must be given under the same file access scope. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes whose file access scopes cover the run's scope, so a Cancel button can stop a loop; an event given under narrower roots or another script gate waits for a run of its own instead. `update()` in the script's own code in the app also pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. `close()` and the close box close a palette unless its `onClose` returns `false`; the end of its engine or the session closes it too. A session keeps at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.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`). From cbf870502a2f4f43c5660301351c2e8c1cca626e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 05:26:28 -0800 Subject: [PATCH 26/34] Scripts: palette state checks use the no-script property lookup Main changed `Interp::find_property` to take `&mut self`, since it now runs the traps of a proxy on the prototype chain. `plain_state` called it through `&Interp`, so the merge of main did not compile (E0596 at crates/js/src/scriptui.rs:2010). It now calls `find_ordinary_property`, which keeps reading `enabled` and `visible` without running any script. --- crates/js/src/scriptui.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 4107b9d38a..ac30d225ca 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -2007,7 +2007,7 @@ fn live_now(i: &Interp, desc: &Value, held: &[Value], at: usize) -> JsResult JsResult { - Ok(match i.find_property(o, &key(name))? { + Ok(match i.find_ordinary_property(o, &key(name))? { Some(Prop::Data { value, .. }) => value.truthy(), _ => false, }) From 2cf9f5619488729af2a1140227eb0ed46c702ff2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 10:49:08 -0800 Subject: [PATCH 27/34] Scripts: palette events keep their file access, hide and enabled checks - update() takes a waiting palette event only when the run's file access roots reach the same files as the event's, so a handler never runs with less access than its palette was shown with. - A palette event is no longer delivered to a handler after its palette was hidden and shown again, or after a capturing listener disabled or hid the control or a group above it. - A limit that ends a handler update() took restores the run's own actions before the end-of-run refresh. - A palette refresh that fails reports no unhandled rejection. - A refused palette field text no longer replaces text typed after it. - The script.run, script.palette.event and docs texts describe update() delivery, list staleness after item edits, and repeating a click or close dropped with an oversized text. --- crates/engine/src/cmd/scripts.rs | 4 +- crates/engine/src/file_access.rs | 24 +++++++---- crates/engine/src/script/mod.rs | 6 +++ crates/engine/src/script/palettes.rs | 6 ++- crates/engine/src/tests/script_palettes.rs | 38 ++++++++++++++---- crates/js/src/realm.rs | 11 +++++- crates/js/src/scriptui.rs | 46 +++++++++++++++++----- crates/js/src/scriptui_tests.rs | 45 +++++++++++++++++++++ crates/ui-egui/src/script_palettes.rs | 3 +- docs/mcp.md | 10 ++--- docs/target-app-parity.md | 2 +- 11 files changed, 158 insertions(+), 37 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index de6f6d251f..074417db20 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 script file (.js, .mjs or .jsx) | 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), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), 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), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; new Window(\"palette\", title) builds a palette the same way, only in a script with #targetengine and a name other than main (elsewhere it throws an error that says so): its show() returns at once and the palette stays open after the run, beside the documents, until close(), the close box (each runs onClose, which can keep it open by returning false) or the end of its engine or the session; each click, change or close the person gives it runs its handler as a run of its own in that engine, once no run is going, oldest first, and a newer one for the same control or the same close takes a waiting one's place (script.palettes, script.palette.event; at most 16 palettes and 64 waiting events); show() on a dialog waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a script file (.js, .mjs or .jsx) | 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), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), 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), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; new Window(\"palette\", title) builds a palette the same way, only in a script with #targetengine and a name other than main (elsewhere it throws an error that says so): its show() returns at once and the palette stays open after the run, beside the documents, until close(), the close box (each runs onClose, which can keep it open by returning false) or the end of its engine or the session; each click, change or close the person gives it runs its handler as a run of its own in that engine, once no run is going, oldest first, unless a run of that engine takes it first with update(), which runs the handler during that run with no report or undo step of its own, and a newer one for the same control or the same close takes a waiting one's place (script.palettes, script.palette.event; at most 16 palettes and 64 waiting events); show() on a dialog waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its 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 ), @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Script Palette Event", [], None, - "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler", + "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler", always, palette_event ), diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 93ef5ec983..2711938b78 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -290,11 +290,6 @@ impl ScopeHandle { Self(Some(scope), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get)) } - /// Whether this scope allows everything the calling thread's scope allows ([`ScopeHandle::covers`]). - pub(crate) fn covers_current(&self) -> bool { - self.covers(&Self::capture()) - } - /// Whether this scope allows everything `other` allows: its roots are none, or each root of /// `other` lies inside one of its roots of the same kind, and its script gate is none or the /// same gate. @@ -304,12 +299,25 @@ impl ScopeHandle { (Some(a), Some(b)) => Arc::ptr_eq(a, b), (Some(_), None) => false, }; - let roots = match (self.roots(), other.roots()) { + gate && self.roots_cover(other) + } + + /// Whether this scope's roots are none, or each root of `other` lies inside one of its roots + /// of the same kind. + fn roots_cover(&self, other: &Self) -> bool { + match (self.roots(), other.roots()) { (None, _) => true, (Some(a), Some(b)) => Arc::ptr_eq(&a, &b) || a.contains(&b), (Some(_), None) => false, - }; - gate && roots + } + } + + /// Whether this scope allows everything the calling thread's scope allows + /// ([`ScopeHandle::covers`]) and the calling thread's roots cover this scope's roots too, so + /// work run in the calling thread's scope reaches the same files this scope reaches. + pub(crate) fn matches_current(&self) -> bool { + let current = Self::capture(); + self.covers(¤t) && current.roots_cover(self) } /// Whether this scope and `other` allow the same: each covers the other, and reads are exempt diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 4fb5cd8617..1fa34e050d 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2988,6 +2988,12 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result Option { - self.waiting.iter().position(|q| q.scope.covers_current() && self.list.iter().any(|p| p.id == q.palette && p.engine == engine)) + self.waiting.iter().position(|q| q.scope.matches_current() && self.list.iter().any(|p| p.id == q.palette && p.engine == engine)) } } diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index a522a0468f..fa57cf5fc5 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -389,7 +389,7 @@ fn repeated_clicks_and_closes_merge_after_the_last_change_of_their_palette() { } #[test] -fn update_takes_events_whose_roots_grant_all_the_run_s_roots_grant() { +fn update_takes_only_events_whose_roots_grant_what_the_run_s_roots_grant() { let mut s = one_doc(); run_in_app( &mut s, @@ -403,12 +403,20 @@ fn update_takes_events_whose_roots_grant_all_the_run_s_roots_grant() { let wide = crate::file_access::AutomationRoots::new(&[&base], &[]).unwrap().unwrap(); let same = crate::file_access::AutomationRoots::new(&[&base], &[]).unwrap().unwrap(); let narrow = crate::file_access::AutomationRoots::new(&[&inner], &[]).unwrap().unwrap(); - for (run_roots, what) in [(same, "the same roots made again"), (narrow, "roots inside the event's roots")] { - assert_eq!(crate::file_access::confine(Some(&wide), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); - let report = crate::file_access::confine(Some(&run_roots), || run_in_app(&mut s, "#targetengine contain\np.update(); vc.log('after');")); - assert_eq!(report["log"], json!(["clicked", "after"]), "{what}: {report}"); - assert_eq!(s.script_palette_events_waiting(), 0, "{what}"); - } + assert_eq!(crate::file_access::confine(Some(&wide), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); + let report = crate::file_access::confine(Some(&same), || run_in_app(&mut s, "#targetengine contain\np.update(); vc.log('after');")); + assert_eq!(report["log"], json!(["clicked", "after"]), "the same roots made again: {report}"); + assert_eq!(s.script_palette_events_waiting(), 0); + // A run whose roots lie inside the event's roots would run the handler with less access than + // the event was given: the event waits for a run of its own. + assert_eq!(crate::file_access::confine(Some(&wide), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); + let report = crate::file_access::confine(Some(&narrow), || run_in_app(&mut s, "#targetengine contain\np.update(); vc.log('after');")); + assert_eq!(report["log"], json!(["after"]), "roots inside the event's roots: {report}"); + assert_eq!(s.script_palette_events_waiting(), 1); + crate::file_access::confine(Some(&wide), || { + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("the handler ended").unwrap()["log"], json!(["clicked"])); + }); let _ = std::fs::remove_dir(inner); } @@ -718,6 +726,22 @@ fn after_a_handler_that_update_runs_throws_the_run_plays_its_own_actions() { assert_eq!(objects(&s), before); } +#[test] +fn after_a_limit_ends_a_handler_that_update_runs_the_refresh_plays_the_run_s_own_actions() { + let mut s = one_doc(); + let (id, _) = acts_palette(&mut s, "for (;;) {}"); + run( + &mut s, + "#targetengine acts\nvar played = 'none'; Object.defineProperty(p, 'text', {get: function () { \ + try { app.doScript('Box', 'Set'); played = 'palette'; } catch (e) { played = 'own'; } return 'P'; }});", + ) + .unwrap(); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(run(&mut s, "#targetengine acts\nplayed = 'none'; p.update();").is_err(), "the handler's loop ends the run"); + let log = run(&mut s, "#targetengine acts\nvc.log(played);").unwrap()["log"].clone(); + assert_eq!(log, json!(["own"]), "the refresh after the limit plays the run's own actions, not the palette's"); +} + #[test] fn a_handler_plays_the_actions_of_the_run_that_showed_its_palette() { let mut s = one_doc(); diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 19d9a1893b..c19acde433 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -751,8 +751,15 @@ impl Realm { self.rejections = self.interp.unhandled(); Ok(()) } - Err(Abrupt::Limit(LimitKind::Fuel)) if total > cap => self.outcome(Err(Abrupt::Limit(LimitKind::Unbroken))).map(drop), - Err(e) => self.outcome(Err(e)).map(drop), + // A refresh that fails reports no rejection, as after any failed run. + Err(Abrupt::Limit(LimitKind::Fuel)) if total > cap => { + self.rejections = (Vec::new(), 0); + self.outcome(Err(Abrupt::Limit(LimitKind::Unbroken))).map(drop) + } + Err(e) => { + self.rejections = (Vec::new(), 0); + self.outcome(Err(e)).map(drop) + } } } diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index ac30d225ca..9bfe267ec2 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -62,9 +62,10 @@ //! gives `paletteClose` the id; a `close()` while `onClose` runs does nothing more. The realm keeps //! each palette the host shows until it closes. `Window.__vcPaletteEvent()` takes an event from the //! host's `paletteEvent` (`{palette, event, id, value, element}`, or `null`, with `element` the id -//! of the control), gives it to that palette as a -//! dialog takes one, and then gives `paletteUpdate` each palette's description; `add()` on a shown -//! palette does the same for that palette, so the host's list of its controls stays in step. +//! of the control), and gives it to that palette as a dialog takes one, without giving +//! `paletteUpdate` any description: the host gets the palettes' controls when the run ends +//! ([`crate::Realm::refresh_script_ui`]). `add()` on a shown palette gives `paletteUpdate` that +//! palette's description, so the host's list of its controls stays in step. //! `update()` on a shown palette, or on a `group` or a `panel` in one, takes each event that waits //! for a palette of the run's engine from the host's `paletteTake` (as `paletteEvent` gives it, or //! `null`) and gives it to its palette, while the host's `palettePending` says one waits, giving @@ -134,6 +135,9 @@ const LIST: &str = "__vcList"; const PALETTE_ID: &str = "__vcPaletteId"; const SHOWN: &str = "__vcShown"; const IN_CLOSE: &str = "__vcInClose"; +/// How many times a palette was hidden: an event it took before a hide is not its event after a +/// later `show()`. +const HIDES: &str = "__vcHides"; /// How many times a list's items were added or removed: a palette's waiting change of the list is /// for the items it had then. const REVISION: &str = "__vcRevision"; @@ -1263,15 +1267,33 @@ fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult /// always takes it. type Taker = Option<(ObjId, ObjId, ObjId)>; -/// Does the palette of `taker` still take its event and hold its control? Always true for a -/// dialog. +/// Does the palette of `taker` still take its event and hold its control, with the control and +/// every container above it enabled and visible as they are now, read without running a getter +/// ([`plain_state`])? Always true for a dialog. fn takes(i: &mut Interp, taker: Taker) -> JsResult { match taker { - Some((win, ev, c)) => Ok(still_takes(i, win, ev, None)? && holds(i, win, c)?), + Some((win, ev, c)) => Ok(still_takes(i, win, ev, None)? && holds(i, win, c)? && live_up(i, win, c)?), None => Ok(true), } } +/// Whether `c` and each container above it, up to and including `top`, are enabled and visible, +/// read without running a getter ([`plain_state`]). +fn live_up(i: &Interp, top: ObjId, c: ObjId) -> JsResult { + let mut at = c; + for _ in 0..=MAX_DEPTH + 1 { + if !plain_state(i, at, "enabled")? || !plain_state(i, at, "visible")? { + return Ok(false); + } + if at == top { + return Ok(true); + } + let Some(p) = object_slot(i, at, PARENT)? else { return Ok(false) }; + at = p; + } + Ok(false) +} + /// [`dispatch`] for the event a palette takes (`taker`): no handler or listener runs once a getter, /// a handler or a listener of the event closed the palette or took the event's control out of it. /// → `None` when that happened. @@ -1636,6 +1658,8 @@ fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { let f = host_fn(i, "paletteHide")?; i.call(&f, &Value::Undefined, &[Value::Number(id)])?; set_slot(i, o, SHOWN, Value::Bool(false))?; + let hides = number_slot(i, o, HIDES)? + 1.0; + set_slot(i, o, HIDES, Value::Number(hides))?; i.put(o, key("visible"), Value::Bool(false), true)?; } Ok(Value::Undefined) @@ -1892,6 +1916,9 @@ fn deliver(i: &mut Interp, answer: Value) -> JsResult { } } let Some(win) = win else { return Ok(Value::Undefined) }; + // A hide from here on, even one a later show() follows, ends the palette's hold on the event. + let hides = number_slot(i, win, HIDES)?; + set_slot(i, ev, HIDES, Value::Number(hides))?; let event = match slot(i, ev, "event")? { Value::String(s) => s.to_rust_string(), _ => String::new(), @@ -2022,13 +2049,14 @@ fn holds_value(i: &mut Interp, win: ObjId, held: &[Value], at: usize) -> JsResul } /// Whether the window `win` still takes the event `ev`: a dialog (`keep` is `Some`) always does, -/// and a palette only while the host shows it under the id the event names. A getter or a handler -/// run for the event may have closed or hidden the palette. +/// and a palette only while the host shows it under the id the event names and it has not been +/// hidden since it took the event. A getter or a handler run for the event may have closed or +/// hidden the palette, and shown it again. fn still_takes(i: &mut Interp, win: ObjId, ev: ObjId, keep: Option<&[Value]>) -> JsResult { if keep.is_some() { return Ok(true); } - if !slot(i, win, SHOWN)?.truthy() { + if !slot(i, win, SHOWN)?.truthy() || number_slot(i, ev, HIDES)? != number_slot(i, win, HIDES)? { return Ok(false); } let id = slot(i, ev, "palette")?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 7917d0241b..57e1917331 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -1223,6 +1223,51 @@ fn a_palette_event_does_not_run_a_handler_whose_getter_hid_the_palette() { assert_eq!(r.run("[reads, clicks].join()").unwrap(), JsValue::String("1,0".into()), "the handler read from a hidden palette does not run"); } +#[test] +fn a_palette_event_does_not_run_a_handler_once_a_listener_hid_and_showed_the_palette_again() { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0, heard = 0; \ + p.addEventListener('click', function () { heard++; p.hide(); p.show(); }, true); \ + b.onClick = function () { clicks++; }; p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!( + r.run("[heard, clicks, p.visible].join()").unwrap(), + JsValue::String("1,0,true".into()), + "a click the palette took before a hide is not its click after the palette shows again" + ); +} + +#[test] +fn a_palette_event_does_not_run_a_handler_once_a_capturing_listener_disabled_its_group() { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run( + "var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); var clicks = 0, heard = 0; \ + g.addEventListener('click', function () { heard++; g.enabled = false; }, true); \ + b.onClick = function () { clicks++; }; p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("[heard, clicks].join()").unwrap(), JsValue::String("1,0".into()), "a control in a disabled group takes no click"); +} + +#[test] +fn a_palette_refresh_that_fails_reports_no_rejection() { + let (mut r, _) = palette_realm(Vec::new()); + r.add_es2015(); + r.run( + "var armed = false; var p = new Window('palette'); p.add('button', undefined, 'Go'); \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'P'; }}); \ + p.show(); Promise.reject(new Error('early')); armed = true;", + ) + .unwrap(); + assert_eq!(r.unhandled_rejection_count(), 1, "the run left the rejection unhandled"); + assert!(r.refresh_script_ui().is_err()); + assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (0, 0), "a failed refresh reports no rejection"); +} + #[test] fn a_palette_list_change_runs_no_on_change_once_an_item_s_text_getter_removed_the_list() { let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index 2cc1d81340..e35d277600 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -405,8 +405,9 @@ fn give( } Err(error) => { if let Some((i, text)) = change { + // A text typed after the refused one stays in the field. if let Some((n, text)) = p.dialog.nodes.get(i).zip(text) { - drafts.insert(n.id, text); + drafts.entry(n.id).or_insert(text); } *change_refused = true; } diff --git a/docs/mcp.md b/docs/mcp.md index 48e9c79a03..adbf8851f0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4135,8 +4135,8 @@ the same controls, handlers and limits: `update()` on the palette, or on a group or panel in it, first runs the handlers of the clicks, changes and closes that wait for the palettes of the run's engine, oldest first, so a Cancel button's `onClick` can stop a loop that calls `update()` (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). - `update()` takes eligible events oldest first. Events whose recorded file access scopes do not cover the run's - scope stay queued for runs of their own, while later eligible events for the same engine can run. Events within + `update()` takes eligible events oldest first. Events whose recorded file access scopes do not reach the same + files as the run's scope stay queued for runs of their own, while later eligible events for the same engine can run. Events within one scope keep their order. A desktop event keeps the scope in force when the widget records it, even if the app hands it to the engine under different automation roots. Each deferred event runs in its recorded scope within the scope in force when its run starts. Each one is checked against the palette as the script and the @@ -4174,9 +4174,9 @@ the same controls, handlers and limits: or `visible` state a getter gives is shown disabled or hidden, and its events are dropped. A list's change is dropped, with no error and no handler run, when a script added or removed the list's items after the person chose and before the app put the change in line. Once the change waits in line, it ends its run with an error when a script added or removed the list's - items, even if the list again holds the same texts, and when an item's text comes from a getter rather than a - plain value. A text typed in a palette's field that is longer than 16 KiB stays in the field with the error in the status bar, and a click or close waits - until it is fixed. An error in a handler that ends its run fails that run like any failed run, puts the + items or changed an item's text, even if the list again holds the same texts, and when an item's text comes from a getter rather than a + plain value. A text typed in a palette's field that is longer than 16 KiB stays in the field with the error in the status bar, and the click or close + given with it is dropped: correct the text, then click or close again. An error in a handler that ends its run fails that run like any failed run, puts the documents back, and leaves the palette open. A handler that a palette's `update()` runs throws its error from that `update()` call: when the script catches it, the run goes on and keeps the handler's changes. In the app, `alert`, `confirm`, `prompt` and a dialog's `show()` throw inside a handler; with nobody to ask, a handler's run has no `answers` and ends at the first of them. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fa5c7d28f6..939fa66612 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1178,7 +1178,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`). - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person and runs the controls' `onClick`, `onChanging` and `onChange` handlers. The window's own callbacks are `onShow`, which runs when `show()` starts, and `onClose`, which runs before the dialog closes and keeps it open when it returns false. `show()` returns the result of `close(result)`, or 1 for the default button and 2 for the cancel button when the button has no `onClick` or click listener and no handler closed the dialog with another result. Controls also take `notify`, size objects a script can set one side of, lists' `find` and `remove`, and `addEventListener` for clicks and changes, which the dialog also takes for `show`; `Window.alert`, `Window.confirm` and `Window.prompt` open the script dialogs; a run over MCP or the command line takes the clicks and changes from a `window` answer. `new Window` and `add` also build a window or a control and the controls inside it from a resource specification (https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/). Other control types throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`. - - Scripts: ScriptUI's `new Window("palette")` makes a palette in a script whose `#targetengine` names an engine other than `main`, and the palette's `show()` shows it beside the documents, where it stays open after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going. A click or change is dropped when its control, or a group above it, is disabled or hidden once the palette is described for the event, or when a getter gives that `enabled` or `visible` state. A newer change for the same control takes a waiting change's place only when no click or close of that palette waits after the waiting change, and a newer click or close takes a waiting one's place only when no change of that palette waits after it; in both cases the two must be given under the same file access scope. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes whose file access scopes cover the run's scope, so a Cancel button can stop a loop; an event given under narrower roots or another script gate waits for a run of its own instead. `update()` in the script's own code in the app also pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. `close()` and the close box close a palette unless its `onClose` returns `false`; the end of its engine or the session closes it too. A session keeps at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.rs`. + - Scripts: ScriptUI's `new Window("palette")` makes a palette in a script whose `#targetengine` names an engine other than `main`, and the palette's `show()` shows it beside the documents, where it stays open after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going, unless a run of that engine takes it first with `update()` (below), which runs the handler during that run. A click or change is dropped when its control, or a group above it, is disabled or hidden once the palette is described for the event, or when a getter gives that `enabled` or `visible` state. A newer change for the same control takes a waiting change's place only when no click or close of that palette waits after the waiting change, and a newer click or close takes a waiting one's place only when no change of that palette waits after it; in both cases the two must be given under the same file access scope. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes whose file access scopes reach the same files as the run's scope, so a Cancel button can stop a loop; an event given under other roots or another script gate waits for a run of its own instead. `update()` in the script's own code in the app also pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. `close()` and the close box close a palette unless its `onClose` returns `false`; the end of its engine or the session closes it too. A session keeps at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.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`). From 4cf6c81e8b697ca03ca0006ca012314fc7e5bc85 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 11:35:22 -0800 Subject: [PATCH 28/34] Scripts: a buffered palette click gives only the texts typed before it A click or close that waited in the palette's line gave the script every text typed in the palette by the time the app took it, including text typed after the click. Each batch of events now keeps the typed texts and their typing scopes as they were in its pass, and the click or close commits only those. A text typed later stays in its field. A text that batch commits keeps the scope it was typed in, a refused text keeps the clicks and closes of later batches out of line, a focus-loss change carrying a text the frame already gave is not given again, and a text the click took without a change leaves its field. --- crates/ui-egui/src/script_palettes.rs | 57 ++++++++++++++++++--- crates/ui-egui/src/tests/script_palettes.rs | 30 +++++++++++ 2 files changed, 79 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index e35d277600..b07deea333 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -34,6 +34,10 @@ pub(crate) fn palette_id(id: u64) -> DialogId { dialog_id((KIND, id)) } +/// One batch of given events: its pass's scope, its own scope, the events, and the typed texts as +/// they were in its pass, each with its typing scope. +type Given = (ScopeHandle, ScopeHandle, Vec, BTreeMap); + /// A shown palette on the window's dialog host. pub(crate) struct PaletteWindow { /// The palette as the session has it, from the last frame. @@ -44,8 +48,9 @@ pub(crate) struct PaletteWindow { draft_scopes: BTreeMap, /// The events the person gave since the app last took them, each with its control by its id, /// and a list's change with the items the person saw, so a run that changes the palette before - /// the app takes them leaves each with its own control. - given: Vec<(ScopeHandle, ScopeHandle, Vec)>, + /// the app takes them leaves each with its own control. Each batch also keeps the typed texts as + /// they were in its pass, so a click or close gives only the texts typed before it. + given: Vec, /// The text each edit field gave the script, by the field's id, while its change waits: the /// field shows it until no change of that field waits, even while the palette's field holds the /// same text, since a run before the change may set the field to another one. @@ -187,7 +192,9 @@ impl PaletteWindow { _ => batches.push((scope, vec![q])), } } - self.given.extend(batches.into_iter().map(|(scope, events)| (here.clone(), scope, events))); + let seen: BTreeMap = + self.drafts.iter().filter_map(|(id, text)| self.draft_scopes.get(id).map(|s| (*id, (text.clone(), s.clone())))).collect(); + self.given.extend(batches.into_iter().map(|(scope, events)| (here.clone(), scope, events, seen.clone()))); } } @@ -292,9 +299,39 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // Texts whose change went in line, typed ones a click or close gave included: the field // shows each until its change no longer waits. let mut accepted = BTreeMap::new(); - for (pass_scope, scope, given) in given { + for (pass_scope, scope, given, seen) in given { let mut events: Vec = given.into_iter().filter_map(|q| script_window::resolved(&p.dialog, q)).collect(); - for (event_scope, event) in drafted(app, &p.dialog, &mut drafts, &mut events, &scope, &pass_scope, &draft_scopes) { + // Only the texts typed by this batch's pass are given with its click or close; a text + // typed in a later pass stays in its field. A text this frame already gave is not given + // again. + let seen: BTreeMap = + seen.into_iter().filter(|(field, (text, _))| accepted.get(field) != Some(text)).collect(); + let mut at_pass: BTreeMap = seen.iter().map(|(field, (text, _))| (*field, text.clone())).collect(); + // Each text keeps the scope it had when it was typed, even when a later pass gave it. + let at_scopes: BTreeMap = seen.into_iter().map(|(field, (_, s))| (field, s)).collect(); + script_window::keep_fields(&p.dialog, &mut at_pass); + // A field's change carrying a text this frame already gave is not given a second time. + events.retain(|e| match e { + UiEvent::Change(i, UiValue::Text(text)) => p.dialog.nodes.get(*i).is_none_or(|n| accepted.get(&n.id) != Some(text)), + _ => true, + }); + let before = at_pass.clone(); + let (batch, refused) = drafted(app, &p.dialog, &mut at_pass, &mut events, &scope, &pass_scope, &at_scopes); + // A refused text keeps every later click and close out of line too. + change_refused |= refused; + // A text the click or close took leaves its field unless a later one was typed there. + for (field, text) in &before { + if !at_pass.contains_key(field) && drafts.get(field) == Some(text) { + drafts.remove(field); + } + } + // A text refused in this batch goes back in its field unless a later one was typed there. + for (field, text) in at_pass { + if before.get(&field) != Some(&text) { + drafts.entry(field).or_insert(text); + } + } + for (event_scope, event) in batch { event_scope.run(|| give(app, ctx, p, &mut drafts, vec![event], &mut change_refused, &mut accepted)); } // A text that went back in its field without a scope of its own takes this one. @@ -317,7 +354,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } /// Commits drafts in dialog order, each under its typing and committing scopes. Every draft is -/// validated before any is removed. A refused draft keeps the click or close out of line. +/// validated before any is removed. A refused draft keeps the click or close out of line. → the +/// events with their scopes, and whether a text was refused. fn drafted( app: &mut VectorcraftApp, w: &ScriptUiDialog, @@ -326,9 +364,11 @@ fn drafted( scope: &ScopeHandle, pass_scope: &ScopeHandle, draft_scopes: &BTreeMap, -) -> Vec<(ScopeHandle, UiEvent)> { +) -> (Vec<(ScopeHandle, UiEvent)>, bool) { + let mut refused = false; if let Some(e) = script_window::keep_refused(w, drafts, events) { app.status(e); + refused = true; } let closing = |e: &UiEvent| matches!(e, UiEvent::Click(_) | UiEvent::Close); let mut changes = Vec::new(); @@ -343,6 +383,7 @@ fn drafted( changes.clear(); events.retain(|e| !closing(e)); app.status(e); + refused = true; } } } @@ -364,7 +405,7 @@ fn drafted( let mut given: Vec<_> = events.drain(..at).map(|e| (scope.clone(), e)).collect(); given.extend(changes); given.extend(events.drain(..).map(|e| (closing_scope.clone(), e))); - given + (given, refused) } /// Puts the events the person gave the palette `p` in line, or shows why one was refused. A diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 4b72675b2e..ef816ce39e 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -455,6 +455,36 @@ fn buffered_passes_keep_a_click_or_close_before_a_later_text_commit() { } } +#[test] +fn a_buffered_click_or_close_does_not_give_a_text_typed_after_it() { + for closing in [UiEvent::Click(2), UiEvent::Close] { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine later\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); t.onChange = function () { vc.log('changed ' + t.text); }; \ + go.onClick = function () { vc.log('clicked ' + t.text); }; \ + p.onClose = function () { vc.log('closed ' + t.text); return false; }; p.show();", + ); + let first = if matches!(closing, UiEvent::Close) { "closed" } else { "clicked" }; + with_palette(&app, id, |w| { + w.type_text(1, "early"); + w.pass(&[], vec![closing]); + w.type_text(1, "later"); + }) + .unwrap(); + follow(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 2); + for expected in ["changed early".to_string(), format!("{first} early")] { + script_runs::poll(&mut app); + run_to_end(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([expected])); + } + assert_eq!(app.session.script_palette_events_waiting(), 0); + assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).unwrap().as_deref(), Some("later")); + } +} + #[test] fn a_click_or_close_commits_drafts_in_dialog_order_across_scopes() { use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; From 79ef692ce50c5ba6b67976a54e138df40ad73b4e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 17:05:59 -0800 Subject: [PATCH 29/34] Scripts: palette events keep their checks after getters and print questions - paletteClose with another engine's palette id no longer drops that palette's waiting events. - A hidden palette is not described after a run or an add, so a throwing getter on it no longer fails the run; script.palettes and docs/mcp.md say a hidden palette lists its controls as they were. - A check box's click rechecks the box after reading its value, so a getter that disables it or closes the palette stops the click. - A list's change rechecks that the list is still enabled and visible after its item texts are read, and is dropped when a getter disabled or hid it. - A waiting palette event does not start its run, or ask for frames, while the last run's print jobs wait for their answer. - script.palette.event's help states that a change merges only after its palette's last waiting click or close. --- crates/engine/src/cmd/scripts.rs | 4 +- crates/engine/src/script/palettes.rs | 2 +- crates/engine/src/tests/script_palettes.rs | 13 ++++++ crates/js/src/scriptui.rs | 15 ++++++- crates/js/src/scriptui_tests.rs | 50 ++++++++++++++++++++++ crates/ui-egui/src/app.rs | 4 +- crates/ui-egui/src/script_palettes.rs | 9 +++- crates/ui-egui/src/tests/script_print.rs | 23 ++++++++++ docs/mcp.md | 3 +- 9 files changed, 115 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 5cca4d282b..560804633e 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "List Script Palettes", [], None, - "{} the ScriptUI palettes that runs in named engines showed and have not closed, shown or hidden, in the order they were first shown, and the events that wait for a run → {palettes: [{id, engine, title, visible, controls: [{index, kind, name, text, enabled, visible, value (check box, radio button, slider, progress bar), items and selection (lists)}]}], waiting: events waiting, limit: 16, waitingLimit: 64}", + "{} the ScriptUI palettes that runs in named engines showed and have not closed, shown or hidden, in the order they were first shown, and the events that wait for a run; a hidden palette lists its controls as they were when it was hidden, until show() shows it again → {palettes: [{id, engine, title, visible, controls: [{index, kind, name, text, enabled, visible, value (check box, radio button, slider, progress bar), items and selection (lists)}]}], waiting: events waiting, limit: 16, waitingLimit: 64}", always, palettes ), @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Script Palette Event", [], None, - "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler", + "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, and a change only if no click or close of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler", always, palette_event ), diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 97435efb25..a63a712918 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -172,9 +172,9 @@ impl Palettes { pub(crate) fn close(&mut self, id: u64, engine: &str) -> bool { let before = self.list.len(); self.list.retain(|p| !(p.id == id && p.engine == engine)); - self.waiting.retain(|q| q.palette != id); let closed = self.list.len() != before; if closed { + self.waiting.retain(|q| q.palette != id); self.actions.retain(|(p, _)| *p != id); } closed diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index fa57cf5fc5..28cf359dc1 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -580,6 +580,19 @@ fn a_palette_click_during_another_run_runs_after_it() { assert_eq!(s.script_palette_events_waiting(), 0); } +#[test] +fn closing_a_palette_id_in_another_engine_keeps_that_palette_s_waiting_events() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + run_in_app(&mut s, "#targetengine other\nvar q = new Window('palette', 'Other'); q.add('button', undefined, 'B'); q.show();"); + let tools = s.script_palettes().iter().find(|p| p.engine == "tools").expect("the tools palette").id; + assert_eq!(s.script_palette_event(tools, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(!s.script_palettes.close(tools, "other"), "the other engine has no palette with that id"); + assert_eq!(s.script_palette_events_waiting(), 1, "the tools palette's click still waits"); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["click 1"])); +} + #[test] fn double_clicks_while_queued_run_once() { let mut s = one_doc(); diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 9bfe267ec2..8864fc1911 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -1406,6 +1406,10 @@ fn click_control(i: &mut Interp, c: ObjId, kind: &str) -> JsResult { fn click_control_for(i: &mut Interp, c: ObjId, kind: &str, taker: Taker) -> JsResult> { if kind == "checkbox" { let on = i.get_value(&Value::Object(c), &key("value"))?.truthy(); + // A `value` getter may have disabled or hidden the box, or closed its palette. + if taker.is_some() && !takes(i, taker)? { + return Ok(None); + } i.put(c, key("value"), Value::Bool(!on), true)?; } else if kind == "radiobutton" { i.put(c, key("value"), Value::Bool(true), true)?; @@ -1791,9 +1795,13 @@ fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { Ok(()) } -/// Gives the host the controls of the palette `win` as they are now, when it shows the palette. +/// Gives the host the controls of the palette `win` as they are now, when it shows the palette. A +/// palette that `hide()` hid is not read: `show()` gives its controls when it shows it again. fn update_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { let Value::Number(id) = slot(i, win, PALETTE_ID)? else { return Ok(()) }; + if !slot(i, win, SHOWN)?.truthy() { + return Ok(()); + } let (desc, ..) = describe(i, win)?; let f = host_fn(i, "paletteUpdate")?; i.rooted(std::slice::from_ref(&desc), |i| i.call(&f, &Value::Undefined, &[desc.clone(), Value::Number(id)]))?; @@ -2318,6 +2326,11 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, if !holds(i, win, c)? { return Err(error(i, "a palette event names a control the palette no longer holds")); } + // An item's text getter may have disabled or hidden the list, or a + // group above it: the event is then dropped, as for a click. + if !live_up(i, win, c)? { + return Ok(()); + } if revised || !same || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { return Err(error(i, "a palette's list changed before the person's choice was taken")); } diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 57e1917331..6e3f5ffa1c 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -1198,6 +1198,56 @@ fn a_palette_list_change_does_not_run_on_change_once_an_item_s_text_getter_close assert_eq!(r.run("[reads, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("2,,null".into())); } +#[test] +fn a_palette_list_change_is_dropped_once_an_item_s_text_getter_disabled_or_hid_the_list() { + for disable in ["l.enabled = false;", "l.visible = false;"] { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The second read of the first item's text, which compares it with the items the person + // saw, disables the list. + r.run(&format!( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () {{ got.push(String(l.selection)); }}; var reads = -1; \ + Object.defineProperty(l.items[0], 'text', {{get: function () {{ if (reads >= 0 && ++reads == 2) {{ {disable} }} return 'a'; }}}}); \ + p.show();" + )) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("none".into()), "{disable}"); + assert_eq!(r.run("[got.join(), String(l.selection)].join()").unwrap(), JsValue::String(",null".into()), "{disable}"); + } +} + +#[test] +fn a_palette_click_does_not_turn_over_a_check_box_its_value_getter_disabled() { + // Whichever read of `value` disables the box, the click neither sets it nor runs its handler. + for read in 1..=4 { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run(&format!( + "var p = new Window('palette'); var c = p.add('checkbox', undefined, 'On'); var clicks = 0, on = false, reads = -1; \ + Object.defineProperty(c, 'value', {{get: function () {{ if (reads >= 0 && ++reads == {read}) {{ c.enabled = false; }} return on; }}, \ + set: function (v) {{ on = v; }}}}); c.onClick = function () {{ clicks++; }}; p.show(); reads = 0;" + )) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + let got = r.run(&format!("reads >= {read} ? [clicks, on].join() : 'not read'")).unwrap(); + assert!(got == JsValue::String("0,false".into()) || (read > 1 && got == JsValue::String("not read".into())), "read {read}: {got:?}"); + } +} + +#[test] +fn a_hidden_palette_is_not_described_after_the_run() { + let (mut r, calls) = palette_realm(Vec::new()); + r.run( + "var p = new Window('palette', 'T'); p.add('button', undefined, 'Go'); p.show(); p.hide(); \ + Object.defineProperty(p, 'text', {get: function () { throw new Error('read'); }});", + ) + .unwrap(); + let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, _)| n == "paletteUpdate").count(); + let before = updates(&calls); + r.refresh_script_ui().expect("a hidden palette's throwing title getter is not read"); + assert_eq!(updates(&calls), before, "the host is not given a hidden palette's controls"); +} + #[test] fn a_palette_event_does_not_run_a_handler_whose_getter_closed_the_palette() { let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 657be1fa62..d3eb43461d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -587,7 +587,7 @@ impl VectorcraftApp { // asks for its frames, and a run that waits for the person goes on at their next input. An // event that waits for an open undo group asks for no frame; the pass that ends the group // asks for the next one (`ui_frame`). - if self.session.script_palette_can_start() { + if crate::script_palettes::can_start(self) { ctx.request_repaint(); } if self.session.script_running() @@ -828,7 +828,7 @@ impl VectorcraftApp { } menus::native::sync(self, &ctx); // A palette event that waited for an undo group this pass ended starts its run next frame. - if self.session.script_palette_can_start() { + if crate::script_palettes::can_start(self) { ctx.request_repaint(); } // Only a field's commit in the pass of the press is the one it made. diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index b07deea333..eed7529753 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -464,11 +464,18 @@ pub(crate) fn with_palette(app: &VectorcraftApp, id: u64, f: impl FnOnce(&mut with_host(app, |host, _| host.get_mut_by_id::(palette_id(id)).map(f)).flatten() } +/// Whether a waiting palette event's run can start now ([`vectorcraft_engine::Session::script_palette_can_start`]): +/// it also waits while the last run's print jobs wait to be approved or canceled, and asks for no +/// frame meanwhile. +pub(crate) fn can_start(app: &VectorcraftApp) -> bool { + app.session.script_palette_can_start() && !crate::script_runs::waiting_for_print(app) +} + /// Starts the run of the oldest waiting palette event when no run is going. → whether one started. /// A run that could not begin shows its own error: the last report is an earlier run's. The run /// lists the printers it may print to ([`crate::print::script_printers`]), as `script.run` does. pub(crate) fn start_next(app: &mut VectorcraftApp) -> bool { - if !app.session.script_palette_can_start() { + if !can_start(app) { return false; } app.session.script_printers = crate::print::script_printers(app); diff --git a/crates/ui-egui/src/tests/script_print.rs b/crates/ui-egui/src/tests/script_print.rs index 327592a654..a8d5c7c030 100644 --- a/crates/ui-egui/src/tests/script_print.rs +++ b/crates/ui-egui/src/tests/script_print.rs @@ -256,6 +256,29 @@ fn the_print_question_waits_while_a_text_field_has_the_keyboard() { assert!(sent.borrow().is_empty()); } +/// A palette's click waits while the last run's print jobs wait for their answer, and runs after it. +#[test] +fn a_palette_click_waits_for_the_answer_to_the_last_runs_print_jobs() { + let (mut app, _, _) = print_app(true); + run( + &mut app, + "#targetengine tools\nvar p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { vc.log('clicked'); }; p.show();", + ); + let id = app.session.script_palettes()[0].id; + run(&mut app, PRINT_TO_LAB); + assert!(app.session.script_prints_waiting() || asking(&app), "the jobs wait for their answer"); + app.session.script_palette_event(id, vectorcraft_engine::script::UiEvent::Click(1)).unwrap(); + for _ in 0..5 { + script_runs::poll(&mut app); + } + assert!(!app.session.script_running(), "the palette's run does not start while the jobs wait"); + assert_eq!(app.session.script_palette_events_waiting(), 1); + cancel(&mut app, PRINT_KIND); + script_runs::poll(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 0, "the click's run starts once the jobs are answered"); +} + /// Cancel, from anyone, drops the jobs and keeps the run's changes. #[test] fn cancel_drops_a_scripts_print_jobs_and_keeps_its_changes() { diff --git a/docs/mcp.md b/docs/mcp.md index d1b3308375..1f627e5d22 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4307,7 +4307,8 @@ the same controls, handlers and limits: `#targetengine`, or with `#targetengine main`, `new Window("palette")` throws an `Error` that says to add a `#targetengine` line (see [Script engines](#script-engines)). - `show()` runs `onShow` and returns `undefined` at once. `hide()` hides the palette, and `show()` shows it again. - `close()` runs `onClose` and closes the palette unless `onClose` returns `false`; the close box does the same. + While a palette is hidden, `script.palettes` lists its controls as they were when it was hidden; `show()` gives + the controls as they are then. `close()` runs `onClose` and closes the palette unless `onClose` returns `false`; the close box does the same. A palette also closes when `script.engine.drop` drops its engine, when its engine ends with an internal error, and when the session ends. The palette shows its controls as `show()`, `add()`, each event's handlers and each run of its engine leave them; a run that a limit or `script.stop` ended can leave it showing them as they were. From 6826f306ae0feabcb3184dc21f9f95b50374272a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 18:15:18 -0800 Subject: [PATCH 30/34] Scripts: palette tests check the post-limit refresh and the list revision The engine test now records what the palette's getter plays only after the handler starts, and asserts that a refresh ran after the limit with the run's own actions. The list test turns the item's text getter back into a plain text before it replaces the items, so only the revision check rejects the choice. --- crates/engine/src/tests/script_palettes.rs | 17 +++++++++++------ crates/js/src/scriptui_tests.rs | 10 ++++++---- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 28cf359dc1..cf873ec324 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -742,17 +742,22 @@ fn after_a_handler_that_update_runs_throws_the_run_plays_its_own_actions() { #[test] fn after_a_limit_ends_a_handler_that_update_runs_the_refresh_plays_the_run_s_own_actions() { let mut s = one_doc(); - let (id, _) = acts_palette(&mut s, "for (;;) {}"); + let (id, _) = acts_palette(&mut s, "started = true; for (;;) {}"); + // The getter records what it plays only once the handler has started, so a read before the + // click is taken does not count. run( &mut s, - "#targetengine acts\nvar played = 'none'; Object.defineProperty(p, 'text', {get: function () { \ - try { app.doScript('Box', 'Set'); played = 'palette'; } catch (e) { played = 'own'; } return 'P'; }});", + "#targetengine acts\nvar started = false; var after = []; Object.defineProperty(p, 'text', {get: function () { \ + var played; try { app.doScript('Box', 'Set'); played = 'palette'; } catch (e) { played = 'own'; } \ + if (started) { after.push(played); } return 'P'; }});", ) .unwrap(); assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); - assert!(run(&mut s, "#targetengine acts\nplayed = 'none'; p.update();").is_err(), "the handler's loop ends the run"); - let log = run(&mut s, "#targetengine acts\nvc.log(played);").unwrap()["log"].clone(); - assert_eq!(log, json!(["own"]), "the refresh after the limit plays the run's own actions, not the palette's"); + assert!(run(&mut s, "#targetengine acts\nstarted = false; after = []; p.update();").is_err(), "the handler's loop ends the run"); + let log = run(&mut s, "#targetengine acts\nvc.log(after.join(' '));").unwrap()["log"].clone(); + let after = log[0].as_str().unwrap_or_default(); + assert!(!after.is_empty(), "the palette is refreshed after the handler hit its limit: {log}"); + assert!(after.split(' ').all(|p| p == "own"), "the refresh after the limit plays the run's own actions, not the palette's: {log}"); } #[test] diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 6e3f5ffa1c..11bde4ca26 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -1099,12 +1099,14 @@ fn a_palette_list_change_after_an_item_s_text_changed_throws() { fn a_palette_list_change_throws_when_an_item_s_text_getter_replaces_the_items() { let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); // The event reads the first item's text twice: for the palette's description, then to compare - // it with the items the person saw. The second read replaces the items with ones of the same - // texts. + // it with the items the person saw. The second read turns the getter back into a plain text and + // replaces the items with ones of the same texts, so only the list's revision tells them apart. r.run( "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ - l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ - Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { l.removeAll(); l.add('item', 'a'); l.add('item', 'b'); } return 'a'; }}); \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; var first = l.items[0]; \ + Object.defineProperty(first, 'text', {configurable: true, get: function () { if (reads >= 0 && ++reads == 2) { \ + Object.defineProperty(first, 'text', {value: 'a', writable: true, enumerable: true, configurable: true}); \ + l.removeAll(); l.add('item', 'a'); l.add('item', 'b'); } return 'a'; }}); \ p.show();", ) .unwrap(); From ced550ebef33475e1c6d00255300d0289ffb8e2d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 22:34:57 -0800 Subject: [PATCH 31/34] Scripts: path points of other Global Edit members go stale when Global Edit changes them While Global Edit is on, an object model edit of one member (or a move of a group that holds it) is given to the other members, but the check that marks read PathPoint handles stale only looked at the edited object's own subtree. A script that read a point of another member kept a valid handle after the edit, even when an undo then put the member back. The check now also looks at each Global Edit member, or the outermost Objects on Path group that holds it, and skips subtrees the command left as they were. The stale-point check came in with #9288. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom/paths.rs | 26 ++++++--- crates/engine/src/tests/script_dom_paths.rs | 65 +++++++++++++++++++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 4 files changed, 88 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index cb23b429b0..752b8ea5b1 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -1375,7 +1375,8 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { /// [`see_points`] for each path whose points the run has read, after each command, so that a /// change that a later command reverses still makes the points stale. Paths under the object that /// the object model is changing ([`super::State`]), or that object itself, take the change as the -/// object model's own, and their points stay valid. A document that is the one the run last looked +/// object model's own, and their points stay valid; the other Global Edit members, which take the +/// object model's edit too, are looked at as well. A document that is the one the run last looked /// at is skipped, as are its paths. pub(super) fn see_all_points(h: &super::Host) { let keys: Vec<(u64, u64)> = { @@ -1384,18 +1385,27 @@ pub(super) fn see_all_points(h: &super::Host) { let seen = h.dom.point_nodes.borrow(); let mut keys = Vec::new(); docs.retain(|uid, before| { - let after = s.documents().iter().find(|d| d.uid == *uid).map(|st| &st.doc); + let state = s.documents().iter().find(|d| d.uid == *uid); + let after = state.map(|st| &st.doc); if after.is_some_and(|after| Arc::ptr_eq(before, after)) { return true; } // Editing a path in an Objects on Path group can move the other paths in the group, so - // the outermost such group is looked at in place of the path. + // the outermost such group is looked at in place of the path. While Global Edit is on, + // an edit of the selected member (also one made by moving a group that holds it) is + // given to the other members, so each of them, or the outermost Objects on Path group + // holding it, is looked at too. Subtrees the command left as they were are skipped. let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) { Some(item) => { - let group = before - .ancestry(item.id) - .and_then(|a| a.into_iter().find(|g| before.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path))); - node_arc(before, group.unwrap_or(item.id)).into_iter().collect() + let root = |id: NodeId| { + before + .ancestry(id) + .and_then(|a| a.into_iter().find(|g| before.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path))) + .unwrap_or(id) + }; + let members = state.and_then(|st| st.global_edit.as_ref()).map(|ge| ge.members.iter().map(|(id, _)| *id)).into_iter().flatten(); + let mut roots = std::collections::HashSet::new(); + std::iter::once(item.id).chain(members).map(root).filter(|id| roots.insert(*id)).filter_map(|id| node_arc(before, id)).collect() } None => before.layers.iter().collect(), }; @@ -1417,6 +1427,8 @@ pub(super) fn see_all_points(h: &super::Host) { false } }); + keys.sort_unstable(); + keys.dedup(); keys }; let editing = h.dom.editing.get(); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 1e4a123d09..3b44785b3a 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1588,6 +1588,71 @@ fn a_point_outside_an_inner_objects_on_path_group_is_stale_after_its_path_change assert_eq!(art(&s), before); } +/// Global Edit gives an edit of one member to the others, so a point read of another member before +/// the edit is stale afterwards, even when an undo puts the member back. +#[test] +fn a_point_of_another_global_edit_member_is_stale_after_an_edit_and_undo() { + let (mut s, a, _) = doc(); + let c = rect(&mut s, 200.0, 100.0, 30.0, 40.0); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "edit"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [c.0], "name": "m"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = s.execute("select.globalEdit", &json!({})).unwrap(); + assert_eq!(r["count"], json!(2), "{r}"); + let before = art(&s); + let out = log( + &mut s, + "var P = app.activeDocument.pathItems, p = P.getByName('edit'), m = P.getByName('m');\ + vc.log(m.pathPoints[0].anchor);\ + var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 10, q.anchor[1]];\ + vc.log(P.getByName('m').pathPoints[0].anchor); app.undo();", + ); + assert_ne!(out[0], out[1], "the other member took the edit"); + assert_eq!(art(&s), before); + let e = failure( + &mut s, + "var P = app.activeDocument.pathItems, p = P.getByName('edit'), m = P.getByName('m');\ + var mp = m.pathPoints[0]; mp.anchor;\ + var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 10, q.anchor[1]]; app.undo();\ + mp.anchor;", + ); + assert!(e.contains("Stale path point"), "{e}"); + assert_eq!(art(&s), before); +} + +/// Moving a group that holds the selected Global Edit member moves the other members too, so a +/// point read of another member before the move is stale afterwards. +#[test] +fn a_point_of_another_global_edit_member_is_stale_after_its_group_moves_and_undoes() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 30.0, 40.0); + s.execute("object.setProps", &json!({"ids": [c.0], "name": "m"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = s.execute("select.globalEdit", &json!({})).unwrap(); + assert_eq!(r["count"], json!(2), "{r}"); + let before = art(&s); + let out = log( + &mut s, + "var P = app.activeDocument.pathItems, m = P.getByName('m');\ + vc.log(m.pathPoints[0].anchor);\ + app.activeDocument.groupItems[0].translate(10, 0);\ + vc.log(P.getByName('m').pathPoints[0].anchor); app.undo();", + ); + assert_ne!(out[0], out[1], "the other member took the move"); + assert_eq!(art(&s), before); + let e = failure( + &mut s, + "var P = app.activeDocument.pathItems, m = P.getByName('m');\ + var mp = m.pathPoints[0]; mp.anchor;\ + app.activeDocument.groupItems[0].translate(10, 0); app.undo();\ + mp.anchor;", + ); + assert!(e.contains("Stale path point"), "{e}"); + assert_eq!(art(&s), before); +} + /// [`doc`] with pattern `Dots` and spot swatch `Ink`, and path `a` with no fill or stroke. fn doc_with_paints() -> (Session, NodeId) { let (mut s, a, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 1419fc3194..c812305400 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3685,7 +3685,9 @@ through `$`: than the object model changed the path's points (a command run with `vc.run`, such as `path.setAnchors`, `object.move` or `edit.undo`); points stay valid through the object model's other changes to the path or to an object that holds it, such as `translate()`. An exception applies when editing another path in an Objects on - Path group moves a path inside that group. Its existing `PathPoint` handles throw `Stale path point`. + Path group moves a path inside that group, and when Global Edit changes another member's path points. + Their existing `PathPoint` handles throw `Stale path point`. An appearance-only change, such as a fill change, + leaves the handles valid. Read those points again from `pathPoints`. Reading a path's points first writes any waiting point changes of another path in the same Objects on Path group. Every point of a path selected as a whole is a selected anchor point, and the endpoints of selected segments are not. Independently selected anchors remain selected alongside segment diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 145e117d67..6358be692f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1116,7 +1116,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked or is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked or is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. From 9803e7438daf69d0fc0753eed3ec7bf62e288120 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 07:03:18 -0800 Subject: [PATCH 32/34] View: Curvature Comb overlay on selected paths View > Show Curvature Comb (view.curvatureComb) draws the curvature comb of the selected paths, and of each path in a selected compound path, while edges show. Each segment gets 16 evenly spaced teeth along the normal, on the outer side of the bend, each as long as the curvature at that point, and a line joins the tips in the path's layer color. A bend with a radius of 100 screen points gives 20-point teeth at any zoom. - vectorcraft-geom: curvature_comb samples the signed curvature of a subpath. Straight segments give teeth of no length, points with no direction give none, and the line through the tips breaks at those points and at cusps between teeth. - The comb draws at most 20,000 teeth, shared among the selected paths by their number of segments, so a large selection gets fewer teeth everywhere instead of losing whole stretches. - The toggle is a view setting: it is not saved in the document, makes no undo step and rejects parameters. Docs: docs/mcp.md, ROADMAP progress log. Fixes #10659 --- ROADMAP.md | 2 + crates/engine/src/cmd/plugin.rs | 2 + crates/geom/src/curvature.rs | 222 ++++++++++++++++++++++ crates/mcp/src/ui_catalog.rs | 6 + crates/ui-egui/src/canvas/marks.rs | 63 ++++++ crates/ui-egui/src/canvas/marks/tests.rs | 40 ++++ crates/ui-egui/src/canvas/tool_adapter.rs | 3 + crates/ui-egui/src/i18n/tests.rs | 1 + crates/ui-egui/src/menus/entries.rs | 3 +- crates/ui-egui/src/menus/labels.rs | 3 + crates/ui-egui/src/menus/model.rs | 2 +- crates/ui-egui/src/menus/run.rs | 4 +- crates/ui-egui/src/menus/tests.rs | 1 + crates/ui-egui/src/menus/tree.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 6 + crates/ui-egui/src/state.rs | 4 + docs/mcp.md | 9 + 17 files changed, 369 insertions(+), 3 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 2b9961f821..9c4e5d22c6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips (#10659). Headline numbers unchanged. + - 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied. - 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index e2ffb44d0c..33b38e567b 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -980,6 +980,8 @@ pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[ (&["View"], "Show Corner Widget"), (&["View"], "Show Live Paint Gaps"), (&["View"], "Hide Live Paint Gaps"), + (&["View"], "Show Curvature Comb"), + (&["View"], "Hide Curvature Comb"), (&["View"], "Guides"), (&["View"], "Smart Guides"), (&["View"], "Perspective Grid"), diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index aea7afde1d..54f5860a31 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -219,12 +219,234 @@ pub fn circular_arc(c: CubicBez) -> Option<(Point, f64)> { ((l0 - handle).abs() <= HANDLE_TOL * handle && (l3 - handle).abs() <= HANDLE_TOL * handle).then_some((center, radius)) } +/// One tooth of a curvature comb: it starts on the curve at `at` and ends at `tip`, along the +/// curve's normal on the side away from its center of curvature, `scale` times the curvature long. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CombTooth { + pub at: Point, + pub tip: Point, + /// The first tooth of the comb, the first after a point or segment that has no tooth, or the + /// first after the curve turns back on itself (a cusp between two teeth): a line through the + /// tips starts again here. + pub start: bool, +} + +/// The most teeth a curvature comb draws in all. +pub const MAX_COMB_TEETH: usize = 20_000; + +/// The curvature comb of `sp`: `samples` teeth on each segment (at least 2), evenly spaced in `t` +/// from 0 to 1, each `scale` times the signed curvature long ([`CombTooth`]). A straight segment +/// gives teeth of no length, its ends included. A point of a curved segment where it has no +/// direction (a handle drawn back onto its anchor) gives no tooth, and neither does a segment +/// with no length, a segment whose points are not finite, or a `scale` that is not finite. When +/// `samples` teeth on every segment would pass `max_teeth`, every segment gets 2 teeth, and when +/// that would still pass it, only every k-th segment gets teeth, spread along the whole subpath. +pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize) -> Vec { + let n = sp.segment_count(); + if n == 0 || !scale.is_finite() || max_teeth < 2 { + return vec![]; + } + let per = if samples.max(2).saturating_mul(n) <= max_teeth { samples.max(2) } else { 2 }; + let stride = (per * n).div_ceil(max_teeth).max(1); + let mut teeth = Vec::with_capacity((per * n / stride).min(max_teeth)); + let mut start = true; + for seg in (0..n).step_by(stride) { + start |= stride > 1; + let c = sp.segment(seg); + if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()) { + start = true; + continue; + } + let (d1, d2) = (c.deriv(), c.deriv().deriv()); + // The control polygon's length sets what counts as no speed. + let size = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + let chord = c.p3 - c.p0; + let line = sp.segment_is_line(seg) && chord.hypot() > 0.0; + let mut previous_direction: Option = None; + for i in 0..per { + if teeth.len() >= max_teeth { + return teeth; + } + let t = i as f64 / (per - 1) as f64; + if line { + // A line stored with its handles on its anchors has no speed at its ends, but a + // direction and no curvature all along. + let at = c.eval(t); + if !at.is_finite() { + start = true; + continue; + } + teeth.push(CombTooth { at, tip: at, start }); + start = false; + continue; + } + let (v, a) = (d1.eval(t).to_vec2(), d2.eval(t).to_vec2()); + let speed = v.hypot(); + if speed <= CUSP_SHARE * size || !speed.is_finite() { + start = true; + continue; + } + let k = v.cross(a) / (speed * speed * speed); + let direction = v / speed; + start |= previous_direction.is_some_and(|previous| previous.dot(direction) < 0.0); + previous_direction = Some(direction); + let normal = Vec2::new(-direction.y, direction.x); + let at = c.eval(t); + let tip = at - normal * (k * scale); + if !at.is_finite() || !tip.is_finite() { + start = true; + continue; + } + teeth.push(CombTooth { at, tip, start }); + start = false; + } + } + teeth +} + #[cfg(test)] mod tests { use super::*; use crate::{Anchor, shapes}; use kurbo::Rect; + fn tooth_len(t: &CombTooth) -> f64 { + t.at.distance(t.tip) + } + + /// A circle's comb points away from the center, each tooth `scale` times the cubic's own + /// curvature at its point ([`curvature_circle_with`] without arcs), all within 3% of + /// `scale / r` (the usual cubic of a quarter turn strays that little from its circle). + #[test] + fn the_comb_of_a_circle_has_teeth_of_one_length() { + let pd = shapes::ellipse(Rect::new(50.0, 50.0, 250.0, 250.0)); + let sp = &pd.subpaths[0]; + let teeth = curvature_comb(sp, 9, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 9 * sp.segment_count()); + assert_eq!(teeth.iter().filter(|t| t.start).count(), 1, "one unbroken comb"); + let center = Point::new(150.0, 150.0); + for (i, t) in teeth.iter().enumerate() { + let (seg, at) = (i / 9, (i % 9) as f64 / 8.0); + let r = curvature_circle_with(sp.segment(seg), at, false, false).unwrap().radius; + assert!((tooth_len(t) * r - 1000.0).abs() < 1e-6, "{t:?} {r}"); + assert!((tooth_len(t) - 10.0).abs() < 0.3, "{t:?}"); + assert!(t.tip.distance(center) > t.at.distance(center), "outward: {t:?}"); + } + } + + /// A straight line has teeth of no length, its two ends included. + #[test] + fn the_comb_of_a_line_is_flat() { + let sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 40.0), Point::new(200.0, 0.0)], false); + let teeth = curvature_comb(&sp, 5, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 10); + assert!(teeth.iter().all(|t| tooth_len(t) < 1e-9), "{teeth:?}"); + assert_eq!(teeth[4].at, Point::new(100.0, 40.0), "the corner has a tooth on each side"); + } + + /// Two quarter circles of radius 100 and 50 that meet in one direction: the teeth double in + /// length at the anchor they share. + #[test] + fn the_comb_jumps_where_the_curvature_does() { + let k = 4.0 / 3.0 * (std::f64::consts::FRAC_PI_8).tan(); + let a0 = Anchor { h_out: Point::new(100.0 * k, 0.0), ..Anchor::corner(Point::new(0.0, 0.0)) }; + let a1 = Anchor { + h_in: Point::new(100.0, 100.0 - 100.0 * k), + h_out: Point::new(100.0, 100.0 + 50.0 * k), + ..Anchor::corner(Point::new(100.0, 100.0)) + }; + let a2 = Anchor { h_in: Point::new(50.0 + 50.0 * k, 150.0), ..Anchor::corner(Point::new(50.0, 150.0)) }; + let sp = SubPath::new(vec![a0, a1, a2], false); + let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 6); + let (before, after) = (tooth_len(&teeth[2]), tooth_len(&teeth[3])); + assert!((after / before - 2.0).abs() < 1e-9, "{before} {after}"); + assert!((before - 10.0).abs() < 0.3, "{before}"); + assert!(teeth[2].at.distance(teeth[3].at) < 1e-9, "both teeth start on the shared anchor"); + } + + /// A segment with no length and a handle drawn back onto its anchor do not panic and give no + /// tooth where the curve has no direction; a scale that is not finite gives no comb. + #[test] + fn the_comb_skips_points_with_no_direction() { + let p = Point::new(10.0, 10.0); + assert!(curvature_comb(&SubPath::polyline(&[p, p], false), 4, 1000.0, MAX_COMB_TEETH).is_empty()); + let curve = SubPath::new( + vec![Anchor { h_out: Point::new(50.0, 0.0), ..Anchor::corner(Point::new(0.0, 0.0)) }, Anchor::corner(Point::new(100.0, 100.0))], + false, + ); + let teeth = curvature_comb(&curve, 5, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4, "the end whose handle sits on its anchor has no tooth: {teeth:?}"); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, false, false]); + let back = SubPath::new( + vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor { h_in: Point::new(50.0, 0.0), ..Anchor::corner(Point::new(100.0, 100.0)) }], + false, + ); + let teeth = curvature_comb(&back, 5, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4, "the start, whose handle sits on its anchor, has no tooth: {teeth:?}"); + assert!(teeth[0].start, "the comb starts after the point with no tooth"); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + assert!(curvature_comb(&curve, 5, f64::NAN, MAX_COMB_TEETH).is_empty()); + } + + /// A cusp between samples starts a new line through the comb's tips after the cusp. + #[test] + fn the_comb_breaks_at_a_cusp_between_samples() { + let bp = kurbo::BezPath::from_svg("M0 0 C100 100 0 100 100 0").unwrap(); + let sp = &crate::PathData::from_bezpath(&bp).subpaths[0]; + let teeth = curvature_comb(sp, 6, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 6, "the cusp falls between teeth"); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, false, true, false, false]); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + } + + /// A tooth whose tip overflows is skipped, and the next finite tooth starts a new envelope. + #[test] + fn the_comb_breaks_after_a_nonfinite_tip() { + let sp = SubPath::new( + vec![ + Anchor::with_handles(Point::new(-1.0, 1.0), Point::new(-1.0, 1.0), Point::new(-1.0 / 3.0, -1.0 / 3.0)), + Anchor::with_handles(Point::new(1.0, 1.0), Point::new(1.0 / 3.0, -1.0 / 3.0), Point::new(1.0, 1.0)), + ], + false, + ); + let teeth = curvature_comb(&sp, 5, f64::MAX, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4, "the middle tooth overflows"); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, true, false]); + assert!(teeth[1].at.x < 0.0 && teeth[2].at.x > 0.0, "the gap is inside the segment"); + } + + /// A speed whose cube underflows gives no tooth, and the first finite tooth starts the comb. + #[test] + fn the_comb_skips_a_tip_when_speed_cubed_underflows() { + let sp = SubPath::new( + vec![ + Anchor::with_handles(Point::ORIGIN, Point::ORIGIN, Point::new(1e-109, 0.0)), + Anchor::with_handles(Point::ORIGIN, Point::new(1e-101, 1e-101), Point::ORIGIN), + ], + false, + ); + let teeth = curvature_comb(&sp, 5, 1.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4, "the first tooth has a nonfinite tip"); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + assert!(teeth[0].start && teeth[0].at.x > 0.0, "the comb starts after the skipped tooth"); + } + + /// A subpath with more segments than the budget allows keeps to it, with teeth spread to its + /// far end rather than stopping part way. + #[test] + fn the_comb_is_capped_and_spread() { + let points: Vec = (0..30_001).map(|i| Point::new(i as f64, (i % 2) as f64)).collect(); + let sp = SubPath::polyline(&points, false); + let teeth = curvature_comb(&sp, 16, 1.0, 1000); + assert!(teeth.len() <= 1000 && teeth.len() >= 900, "{}", teeth.len()); + assert!(teeth.last().is_some_and(|t| t.at.x > 29_000.0), "{:?}", teeth.last()); + assert_eq!(teeth.iter().filter(|t| t.start).count() * 2, teeth.len(), "each sampled segment starts a new line through the tips"); + let few = curvature_comb(&sp, 16, 1.0, 100_000); + assert_eq!(few.len(), 60_000, "too many for 16 on each, so 2 on each"); + } + /// Every segment of a circle drawn by [`shapes::ellipse`] is the usual cubic of a quarter /// turn, and the circle at any point of it is the circle itself: radius 100, center (150, 150). #[test] diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index acbbb5d151..efc31ac652 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -261,6 +261,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} toggle drawing the gaps of the selected Live Paint groups (those livePaint.info lists) in each group's Gap Preview Color while edges show → true when on", ), + ( + "view.curvatureComb", + "Show Curvature Comb", + "", + "{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on", + ), ( "type.hiddenCharacters", "Show Hidden Characters", diff --git a/crates/ui-egui/src/canvas/marks.rs b/crates/ui-egui/src/canvas/marks.rs index abe7c5a6db..4e8c3776f0 100644 --- a/crates/ui-egui/src/canvas/marks.rs +++ b/crates/ui-egui/src/canvas/marks.rs @@ -835,3 +835,66 @@ pub(in crate::canvas) fn live_paint_gap_overlays(app: &mut VectorcraftApp) -> Ve }; gaps.to_vec() } + +/// Teeth View → Show Curvature Comb draws on each segment. +const COMB_SAMPLES: usize = 16; +/// The comb's length at zoom 1, in screen points squared: a curve that bends with a radius of +/// 100 screen points has teeth 20 screen points long at any zoom. VectorCraft's own value. +const COMB_SCALE: f64 = 2000.0; + +/// View → Show Curvature Comb: on each selected path, and each path of a selected compound path, a +/// tooth along the normal at evenly spaced points of every segment, as long as the curvature there, +/// and a line through the teeth's tips, in the path's layer color. At most +/// [`vectorcraft_geom::curvature::MAX_COMB_TEETH`] teeth in all, shared among the subpaths by their +/// number of segments, so a large selection gets fewer teeth everywhere. +pub(in crate::canvas) fn curvature_comb_overlays(app: &VectorcraftApp, zoom: f64) -> Vec { + use vectorcraft_geom::curvature::{MAX_COMB_TEETH, curvature_comb}; + let Some(st) = app.session.active() else { return vec![] }; + if !(zoom.is_finite() && zoom > 0.0) { + return vec![]; + } + let scale = COMB_SCALE / (zoom * zoom); + let mut paths = vec![]; + for &id in &st.selection.objects { + let Some(n) = st.doc.node(id).filter(|n| !n.is_guide()) else { continue }; + let color = st.doc.layer_color(id); + match &n.kind { + NodeKind::Compound { children, .. } => paths.extend(children.iter().filter_map(|c| c.path_data()).map(|pd| (pd, color))), + _ => paths.extend(n.path_data().map(|pd| (pd, color))), + } + } + let all: Vec<_> = + paths.iter().flat_map(|(pd, color)| pd.subpaths.iter().map(move |sp| (sp, *color))).filter(|(sp, _)| sp.segment_count() > 0).collect(); + // With more subpaths than the teeth allow 2 each, every k-th subpath gets a comb. + let stride = (all.len() * 2).div_ceil(MAX_COMB_TEETH).max(1); + let chosen: Vec<_> = all.into_iter().step_by(stride).collect(); + // Each chosen subpath has 2 teeth set aside; the rest are shared by number of segments. + let total: usize = chosen.iter().map(|(sp, _)| sp.segment_count()).sum(); + let spare = MAX_COMB_TEETH.saturating_sub(2 * chosen.len()); + let mut o = vec![]; + for (sp, color) in chosen { + let extra = (spare as u128) * (sp.segment_count() as u128) / (total.max(1) as u128); + let share = 2usize.saturating_add(usize::try_from(extra).unwrap_or(usize::MAX)); + let teeth = curvature_comb(sp, COMB_SAMPLES, scale, share); + let mut envelope = BezPath::new(); + for t in &teeth { + o.push(Overlay::Line { a: t.at, b: t.tip, color, dashed: false }); + if t.start { + envelope.move_to(t.tip); + } else { + envelope.line_to(t.tip); + } + } + // A closed subpath combed all the way round ends where it starts: the line closes there. + let unbroken = teeth.iter().filter(|t| t.start).count() == 1; + if let (true, true, Some(first), Some(last)) = (sp.closed, unbroken, teeth.first(), teeth.last()) + && first.at.distance(last.at) < 1e-9 + { + envelope.line_to(first.tip); + } + if teeth.len() > 1 { + o.push(Overlay::Path { path: envelope, color, width: 1.0, dashed: false }); + } + } + o +} diff --git a/crates/ui-egui/src/canvas/marks/tests.rs b/crates/ui-egui/src/canvas/marks/tests.rs index 29336a8ad8..621a7b67e2 100644 --- a/crates/ui-egui/src/canvas/marks/tests.rs +++ b/crates/ui-egui/src/canvas/marks/tests.rs @@ -359,6 +359,46 @@ fn live_paint_gaps_follow_the_selected_groups() { assert!(live_paint_gap_overlays(&mut app).is_empty()); } +/// View → Show Curvature Comb: a selected circle of radius 100 gets teeth 20 screen points long at +/// zoom 1 and 10 at zoom 2, where it shows twice as large (within 3%: the circle is made of cubics), +/// and a line through their tips; a compound path gets a comb on each of its paths; nothing +/// selected draws nothing. +#[test] +fn the_curvature_comb_follows_the_selection_and_the_zoom() { + let mut app = app(); + let id = app.session.execute("shape.ellipse", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let teeth = |o: &[Overlay], zoom: f64| -> Vec { + o.iter().filter_map(|o| if let Overlay::Line { a, b, .. } = o { Some(a.distance(*b) * zoom) } else { None }).collect() + }; + let at_one = teeth(&curvature_comb_overlays(&app, 1.0), 1.0); + for zoom in [1.0, 2.0] { + let o = curvature_comb_overlays(&app, zoom); + let got = teeth(&o, zoom); + assert_eq!(got.len(), 64, "16 teeth on each of the circle's four segments"); + let want = 2000.0 / (100.0 * zoom); + assert!(got.iter().all(|t| (t - want).abs() < 0.03 * want), "{zoom}: {got:?}"); + assert!(got.iter().zip(&at_one).all(|(t, one)| (t * zoom - one).abs() < 1e-9), "zoom divides each tooth's screen length"); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Path { .. })).count(), 1, "one line through the tips"); + let Some(Overlay::Path { path, .. }) = o.iter().find(|o| matches!(o, Overlay::Path { .. })) else { panic!("no line through the tips") }; + let ends: Vec<_> = path.elements().iter().filter_map(|e| e.end_point()).collect(); + assert_eq!(ends.first(), ends.last(), "the closed circle's line through the tips closes"); + } + let other = app.session.execute("shape.ellipse", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [id, other]})).unwrap(); + app.session.execute("object.compoundPath.make", &json!({})).unwrap(); + let o = curvature_comb_overlays(&app, 1.0); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Path { .. })).count(), 2, "the compound path's two paths"); + assert_eq!(teeth(&o, 1.0).len(), 128); + app.session.execute("select.set", &json!({"ids": []})).unwrap(); + assert!(curvature_comb_overlays(&app, 1.0).is_empty()); + assert!(app.run("view.curvatureComb", json!({"on": true})).is_err(), "it takes no parameters"); + assert!(!app.ui.view.curvature_comb, "a refused call leaves it off"); + assert!(app.run("view.curvatureComb", json!({})).unwrap() == json!(true)); + assert!(app.ui.view.curvature_comb); + assert!(app.run("view.curvatureComb", json!({})).unwrap() == json!(false)); +} + /// Draw Inside's arms: an open rectangle round the object, each arm a third of its side or 16 /// points at most, kept with the object deselected and gone with the mode. #[test] diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 8b2b35db16..9ae5044d0d 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -771,6 +771,9 @@ fn show_overlays(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass, view_in if app.ui.view.live_paint_gaps { extra.extend(super::marks::live_paint_gap_overlays(app)); } + if app.ui.view.curvature_comb { + extra.extend(super::marks::curvature_comb_overlays(app, space.view.zoom)); + } } super::overlays::show(app, ui, &space, &list, &extra); } diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index e77c4bae56..cdbc54b58d 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1035,6 +1035,7 @@ fn toggled_labels() -> Vec { "type.hiddenCharacters", "view.gradientAnnotator", "view.livePaintGaps", + "view.curvatureComb", "view.artboards", "view.template", "view.rulers", diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 66353c55be..71feba3195 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -76,7 +76,7 @@ const MENU_ONLY_COMMANDS: [&str; 5] = ["imageTrace.make", "imageTrace.makeAndExp /// action ([`plays_in_app`]): Outline, Pixel Preview, Trim View, Presentation Mode and Screen Mode, /// the zoom, fit and rotate view items, and the items that show or hide or turn snapping on or off. /// The saved-view slots are not among them. -const UI_STEP_COMMANDS: [&str; 30] = [ +const UI_STEP_COMMANDS: [&str; 31] = [ "view.outline", "view.pixelPreview", "view.trimView", @@ -100,6 +100,7 @@ const UI_STEP_COMMANDS: [&str; 30] = [ "view.gradientAnnotator", "view.cornerWidget", "view.livePaintGaps", + "view.curvatureComb", "view.guides", "view.smartGuides", "view.grid", diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 549d31b876..52ec3b33aa 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -29,6 +29,7 @@ fn view_toggle_label(app: &VectorcraftApp, id: &str) -> Option { "type.hiddenCharacters" => if v.hidden_chars { "Hide Hidden Characters" } else { "Show Hidden Characters" }.into(), "view.gradientAnnotator" => if v.gradient_annotator { "Hide Gradient Annotator" } else { "Show Gradient Annotator" }.into(), "view.livePaintGaps" => if v.live_paint_gaps { "Hide Live Paint Gaps" } else { "Show Live Paint Gaps" }.into(), + "view.curvatureComb" => if v.curvature_comb { "Hide Curvature Comb" } else { "Show Curvature Comb" }.into(), _ => return None, }; Some(text) @@ -356,6 +357,8 @@ pub const DYNAMIC_LABELS: &[&str] = &[ "Show Gradient Annotator", "Hide Live Paint Gaps", "Show Live Paint Gaps", + "Hide Curvature Comb", + "Show Curvature Comb", "Hide Artboards", "Show Artboards", "Hide Rulers", diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 73a4296dd9..bd406aabcc 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -133,7 +133,7 @@ fn rows_key(app: &VectorcraftApp, input: Option) -> u64 { let (prefs, v) = (&s.prefs, &app.ui.view); (prefs.font_preview, prefs.font_samples_on_white, prefs.font_names_in_english, crate::workspaces::current_name(&app.ui)).hash(&mut h); (v.edges, v.templates, v.corner_widgets, v.shape_widgets, v.text_threads, v.hidden_chars, v.gradient_annotator).hash(&mut h); - (v.live_paint_gaps, v.artboards, v.rulers, v.video_rulers, v.bounding_box, v.guides, v.grid).hash(&mut h); + (v.live_paint_gaps, v.curvature_comb, v.artboards, v.rulers, v.video_rulers, v.bounding_box, v.guides, v.grid).hash(&mut h); (app.outline_view(), s.guides_locked(), s.slices_hidden()).hash(&mut h); // The Align To choice: Object › Align's checks and the Distribute buttons with the Artboard tool. app.ui.align_to.hash(&mut h); diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 50e2a7606e..35b09d45b6 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -408,7 +408,7 @@ fn run_ui_part3(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Option> { +fn run_ui_part4(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option> { let flag = |b: &mut bool| { *b = !*b; Ok(json!(*b)) @@ -419,6 +419,8 @@ fn run_ui_part4(app: &mut VectorcraftApp, id: &str, _p: &Value) -> Option crate::panels::align::run_align_to(app, v), "view.gradientAnnotator" => flag(&mut app.ui.view.gradient_annotator), "view.livePaintGaps" => flag(&mut app.ui.view.live_paint_gaps), + "view.curvatureComb" if !(p.is_null() || p.as_object().is_some_and(|m| m.is_empty())) => Err("view.curvatureComb takes no parameters".into()), + "view.curvatureComb" => flag(&mut app.ui.view.curvature_comb), "effect.last" => match app.last_effect.clone() { Some((e, params)) => crate::dialogs::effect::open_last(app, &e, params), None => Err("no effect applied yet".into()), diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 88c2e04540..3f53a3194d 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -626,6 +626,7 @@ fn last_effect_dialog_and_view_toggles() { ("view.textThreads", "Hide Text Threads", "Show Text Threads"), ("view.gradientAnnotator", "Hide Gradient Annotator", "Show Gradient Annotator"), ("view.livePaintGaps", "Show Live Paint Gaps", "Hide Live Paint Gaps"), + ("view.curvatureComb", "Show Curvature Comb", "Hide Curvature Comb"), ("type.hiddenCharacters", "Show Hidden Characters", "Hide Hidden Characters"), ("view.template", "Hide Template", "Show Template"), ] { diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 7cd830ef05..e044ac2580 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -678,6 +678,7 @@ fn built_in_tree(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec c("Hide Gradient Annotator", "view.gradientAnnotator"), c("Hide Corner Widget", "view.cornerWidget"), c("Show Live Paint Gaps", "view.livePaintGaps"), + c("Show Curvature Comb", "view.curvatureComb"), Sep, sub( "Guides", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index e131421a2a..54db93ca34 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -262,6 +262,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} toggle drawing the gaps of the selected Live Paint groups (those livePaint.info lists) in each group's Gap Preview Color while edges show → true when on", ), + ( + "view.curvatureComb", + "Show Curvature Comb", + "", + "{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on", + ), ( "type.hiddenCharacters", "Show Hidden Characters", diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 990d245bc3..3b86fee727 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -410,6 +410,9 @@ pub struct ViewFlags { /// Preview Color. #[serde(default)] pub live_paint_gaps: bool, + /// View → Show/Hide Curvature Comb: draw the curvature comb of the selected paths. + #[serde(default)] + pub curvature_comb: bool, /// Type → Show Hidden Characters. pub hidden_chars: bool, /// Edit › Spelling › Auto Spell Check: a red underline under the words of the type its @@ -443,6 +446,7 @@ impl Default for ViewFlags { text_threads: true, gradient_annotator: true, live_paint_gaps: false, + curvature_comb: false, hidden_chars: false, auto_spell_check: false, templates: true, diff --git a/docs/mcp.md b/docs/mcp.md index 30ac0bfb82..5bb5f438c9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9386,6 +9386,15 @@ of more than half a degree and the anchor is not marked smooth with both handles marked smooth), when the circle would reach past the canvas (4,000,000 pt from the origin), when `t` is not from 0 to 1, when `id` is a guide, and when the path, subpath or segment does not exist. +`view.curvatureComb` (View › Show Curvature Comb, or Hide Curvature Comb while it is on) turns on the curvature comb +of the selected paths, and of each path in a selected compound path, while edges show. Each segment gets 16 evenly +spaced teeth along the normal, on the outer side of the bend, each as long as the curvature at that point, and a line +joins the teeth's tips, in the path's layer color. A straight segment has teeth of no length, and a point of a curve +where it has no direction (a handle on its anchor) has no tooth. The length is VectorCraft's own value: a bend with a +radius of 100 screen points draws 20-point teeth at any zoom. The comb draws about 20,000 teeth at most, shared among +the selected paths by their number of segments: a larger selection gets 2 teeth per segment, then teeth on every k-th +segment. The setting belongs to the view: it is not saved in the document and makes no undo step. + The Curvature Circle tool, after the Circle tool in the Ellipse tool's toolbar group, draws with this command. The pointer snaps to the nearest path that is not a guide within the tool's Snap Tolerance (`snapTolerance` below, 5 screen points by default), or within Smart Guides › Snapping Tolerance when that is larger; with Snap with Smart From 80e8c74d5535e2229bbeb7ffdbd28f6f73155989 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 07:57:29 -0800 Subject: [PATCH 33/34] View: Curvature Comb breaks at a cusp on an anchor The direction of the last curved tooth now carries from one segment to the next, so a cusp where two curved segments meet starts a new line through the tips. It is cleared wherever a tooth is left out, on a line and between strided segments. A closed comb now closes at its first anchor when the curve goes on there without turning back (comb_closes), instead of only when the comb has no break at all, so a cusp elsewhere does not open the join. --- crates/geom/src/curvature.rs | 66 +++++++++++++++++++++++++++++- crates/ui-egui/src/canvas/marks.rs | 7 ++-- 2 files changed, 67 insertions(+), 6 deletions(-) diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index 54f5860a31..52054363e4 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -250,11 +250,18 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize let stride = (per * n).div_ceil(max_teeth).max(1); let mut teeth = Vec::with_capacity((per * n / stride).min(max_teeth)); let mut start = true; + // The direction of the last curved tooth, carried across segments so that a cusp at an + // anchor also starts a new line through the tips. + let mut previous_direction: Option = None; for seg in (0..n).step_by(stride) { - start |= stride > 1; + if stride > 1 { + start = true; + previous_direction = None; + } let c = sp.segment(seg); if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()) { start = true; + previous_direction = None; continue; } let (d1, d2) = (c.deriv(), c.deriv().deriv()); @@ -262,7 +269,6 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize let size = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); let chord = c.p3 - c.p0; let line = sp.segment_is_line(seg) && chord.hypot() > 0.0; - let mut previous_direction: Option = None; for i in 0..per { if teeth.len() >= max_teeth { return teeth; @@ -272,6 +278,7 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize // A line stored with its handles on its anchors has no speed at its ends, but a // direction and no curvature all along. let at = c.eval(t); + previous_direction = None; if !at.is_finite() { start = true; continue; @@ -284,6 +291,7 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize let speed = v.hypot(); if speed <= CUSP_SHARE * size || !speed.is_finite() { start = true; + previous_direction = None; continue; } let k = v.cross(a) / (speed * speed * speed); @@ -295,6 +303,7 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize let tip = at - normal * (k * scale); if !at.is_finite() || !tip.is_finite() { start = true; + previous_direction = None; continue; } teeth.push(CombTooth { at, tip, start }); @@ -304,6 +313,23 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize teeth } +/// Does the line through the tips of `teeth`, the comb of `sp` ([`curvature_comb`]), close where +/// it starts: `sp` is closed, its first and last teeth sit on the same point, and the curve does +/// not turn back on itself at its first anchor. +pub fn comb_closes(sp: &SubPath, teeth: &[CombTooth]) -> bool { + let (Some(first), Some(last)) = (teeth.first(), teeth.last()) else { + return false; + }; + if !sp.closed || teeth.len() < 2 || first.at.distance(last.at) >= 1e-9 { + return false; + } + let n = sp.segment_count(); + match (neighbor(sp, 0, false), neighbor(sp, n.saturating_sub(1), true)) { + (Some((into, _)), Some((out, _))) => end_direction(into).dot(start_direction(out)) >= 0.0, + _ => false, + } +} + #[cfg(test)] mod tests { use super::*; @@ -363,6 +389,42 @@ mod tests { assert!((after / before - 2.0).abs() < 1e-9, "{before} {after}"); assert!((before - 10.0).abs() < 0.3, "{before}"); assert!(teeth[2].at.distance(teeth[3].at) < 1e-9, "both teeth start on the shared anchor"); + assert_eq!(teeth.iter().filter(|t| t.start).count(), 1, "a smooth anchor keeps one unbroken comb"); + } + + /// Two segments that meet at a cusp on their shared anchor: the first segment ends heading + /// down and the second starts heading up, so the line through the tips starts again there. + #[test] + fn the_comb_breaks_at_a_cusp_on_an_anchor() { + let a0 = Anchor { h_out: Point::new(0.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) }; + let a1 = Anchor { h_in: Point::new(100.0, -50.0), h_out: Point::new(100.0, -25.0), ..Anchor::corner(Point::new(100.0, 0.0)) }; + let a2 = Anchor { h_in: Point::new(200.0, -25.0), ..Anchor::corner(Point::new(200.0, 0.0)) }; + let sp = SubPath::new(vec![a0, a1, a2], false); + let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 6); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, false, true, false, false]); + assert!(!comb_closes(&sp, &teeth), "an open subpath does not close"); + } + + /// A closed comb closes at its first anchor when the curve goes on smoothly there, even with a + /// cusp elsewhere, and stays open when the first anchor is the cusp. + #[test] + fn the_comb_closes_unless_its_first_anchor_is_a_cusp() { + let closed = |h_in: Point| { + let a0 = Anchor { h_in, h_out: Point::new(0.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) }; + let a1 = Anchor { h_in: Point::new(100.0, -50.0), h_out: Point::new(100.0, -25.0), ..Anchor::corner(Point::new(100.0, 0.0)) }; + let a2 = Anchor { h_in: Point::new(200.0, -25.0), h_out: Point::new(200.0, 50.0), ..Anchor::corner(Point::new(200.0, 0.0)) }; + SubPath::new(vec![a0, a1, a2], true) + }; + let smooth = closed(Point::new(0.0, 50.0)); + let teeth = curvature_comb(&smooth, 3, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.iter().filter(|t| t.start).count(), 2, "the cusp at the second anchor breaks the comb"); + assert!(comb_closes(&smooth, &teeth)); + let cusp = closed(Point::new(0.0, -50.0)); + assert!(!comb_closes(&cusp, &curvature_comb(&cusp, 3, 1000.0, MAX_COMB_TEETH))); + let circle = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)); + let sp = &circle.subpaths[0]; + assert!(comb_closes(sp, &curvature_comb(sp, 5, 1000.0, MAX_COMB_TEETH))); } /// A segment with no length and a handle drawn back onto its anchor do not panic and give no diff --git a/crates/ui-egui/src/canvas/marks.rs b/crates/ui-egui/src/canvas/marks.rs index 4e8c3776f0..9993669339 100644 --- a/crates/ui-egui/src/canvas/marks.rs +++ b/crates/ui-egui/src/canvas/marks.rs @@ -848,7 +848,7 @@ const COMB_SCALE: f64 = 2000.0; /// [`vectorcraft_geom::curvature::MAX_COMB_TEETH`] teeth in all, shared among the subpaths by their /// number of segments, so a large selection gets fewer teeth everywhere. pub(in crate::canvas) fn curvature_comb_overlays(app: &VectorcraftApp, zoom: f64) -> Vec { - use vectorcraft_geom::curvature::{MAX_COMB_TEETH, curvature_comb}; + use vectorcraft_geom::curvature::{MAX_COMB_TEETH, comb_closes, curvature_comb}; let Some(st) = app.session.active() else { return vec![] }; if !(zoom.is_finite() && zoom > 0.0) { return vec![]; @@ -886,9 +886,8 @@ pub(in crate::canvas) fn curvature_comb_overlays(app: &VectorcraftApp, zoom: f64 } } // A closed subpath combed all the way round ends where it starts: the line closes there. - let unbroken = teeth.iter().filter(|t| t.start).count() == 1; - if let (true, true, Some(first), Some(last)) = (sp.closed, unbroken, teeth.first(), teeth.last()) - && first.at.distance(last.at) < 1e-9 + if let Some(first) = teeth.first() + && comb_closes(sp, &teeth) { envelope.line_to(first.tip); } From c618b9b22cfd4b02cdd4a00ca079c7aee1ef729b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:02:42 -0800 Subject: [PATCH 34/34] View: Curvature Comb does not close across segments a capped comb skips When a long subpath has more segments than the tooth budget, only every k-th segment gets teeth. comb_closes compared only the first and last tooth positions, so a last sampled segment that ended on the first anchor joined its tip to the first tooth across the skipped closing segment. Each tooth now records its segment, and the comb closes only when the segments between the last tooth and the first across the seam have no length. --- crates/geom/src/curvature.rs | 47 ++++++++++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 5 deletions(-) diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index 52054363e4..c36279ee76 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -229,6 +229,8 @@ pub struct CombTooth { /// first after the curve turns back on itself (a cusp between two teeth): a line through the /// tips starts again here. pub start: bool, + /// The index of the segment the tooth sits on. + pub segment: usize, } /// The most teeth a curvature comb draws in all. @@ -283,7 +285,7 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize start = true; continue; } - teeth.push(CombTooth { at, tip: at, start }); + teeth.push(CombTooth { at, tip: at, start, segment: seg }); start = false; continue; } @@ -306,7 +308,7 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize previous_direction = None; continue; } - teeth.push(CombTooth { at, tip, start }); + teeth.push(CombTooth { at, tip, start, segment: seg }); start = false; } } @@ -314,16 +316,23 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize } /// Does the line through the tips of `teeth`, the comb of `sp` ([`curvature_comb`]), close where -/// it starts: `sp` is closed, its first and last teeth sit on the same point, and the curve does -/// not turn back on itself at its first anchor. +/// it starts: `sp` is closed, only segments with no length lie between its last tooth and its +/// first across the seam, the two sit on the same point, and the curve does not turn back on itself at its +/// first anchor. A comb that skips segments to keep to its budget does not close across the ones +/// it skipped at the end. pub fn comb_closes(sp: &SubPath, teeth: &[CombTooth]) -> bool { let (Some(first), Some(last)) = (teeth.first(), teeth.last()) else { return false; }; + let n = sp.segment_count(); if !sp.closed || teeth.len() < 2 || first.at.distance(last.at) >= 1e-9 { return false; } - let n = sp.segment_count(); + // Only segments with no length may lie between the last tooth and the first across the seam. + let no_length = |i: usize| start_direction(sp.segment(i)) == Vec2::ZERO; + if !(last.segment + 1..n).chain(0..first.segment).all(no_length) { + return false; + } match (neighbor(sp, 0, false), neighbor(sp, n.saturating_sub(1), true)) { (Some((into, _)), Some((out, _))) => end_direction(into).dot(start_direction(out)) >= 0.0, _ => false, @@ -509,6 +518,34 @@ mod tests { assert_eq!(few.len(), 60_000, "too many for 16 on each, so 2 on each"); } + /// A capped comb that skips the last segment does not close, even when the last segment it + /// samples ends on the first anchor: the line through the tips would cross the skipped loop. + #[test] + fn a_capped_comb_does_not_close_across_a_skipped_segment() { + let sp = SubPath::new( + vec![ + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(-50.0, -50.0), Point::new(50.0, 50.0)), + Anchor::with_handles(Point::new(100.0, 0.0), Point::new(80.0, 40.0), Point::new(120.0, 20.0)), + Anchor::with_handles(Point::new(100.0, 100.0), Point::new(140.0, 80.0), Point::new(60.0, 140.0)), + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(30.0, 120.0), Point::new(-60.0, 60.0)), + ], + true, + ); + let teeth = curvature_comb(&sp, 16, 1000.0, 4); + let (first, last) = (&teeth[0], &teeth[teeth.len() - 1]); + assert!(last.segment < 3, "the closing segment is skipped: {teeth:?}"); + assert!(first.at.distance(last.at) < 1e-9, "the last sampled tooth sits on the first anchor"); + assert!(!comb_closes(&sp, &teeth), "the comb does not close across the skipped last segment"); + assert!(comb_closes(&sp, &curvature_comb(&sp, 16, 1000.0, MAX_COMB_TEETH)), "the full comb closes"); + let mut anchors: Vec = sp.anchors.iter().copied().collect(); + anchors[0].h_in = anchors[0].p; + anchors.insert(0, Anchor { h_in: Point::new(-50.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) }); + let seam = SubPath::new(anchors, true); + let full = curvature_comb(&seam, 16, 1000.0, MAX_COMB_TEETH); + assert_eq!(full.first().map(|t| t.segment), Some(1), "the segment of no length at the seam has no teeth"); + assert!(comb_closes(&seam, &full), "the comb closes across a segment of no length"); + } + /// Every segment of a circle drawn by [`shapes::ellipse`] is the usual cubic of a quarter /// turn, and the circle at any point of it is the circle itself: radius 100, center (150, 150). #[test]