From 58292d605af4e21822b7f4d0bcf7aa94a2a2838e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:23:19 -0800 Subject: [PATCH] Scripts: app.showColorPicker asks for a color app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor and returns the color picked for OK. Cancel, and OK with the color unchanged, return a new object of the color the script gave. Anything else throws a TypeError. - In the app the run waits at the picker, which previews nothing on the selection. Stop and quitting end the run as at the other script dialogs and close the picker. - A run with nobody to ask takes {kind: "colorPicker", value: color | null} from answers. The report lists the picker with the color it opened on and the answer. - script.run's params text, docs/mcp.md and the Scripts line in docs/target-app-parity.md describe it. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/dialogs.rs | 112 +++++++++++++++++---- crates/engine/src/script/dom.rs | 10 ++ crates/engine/src/script/dom/colors.rs | 14 ++- crates/engine/src/tests/script_dialogs.rs | 72 +++++++++++++ crates/ui-egui/src/dialogs/color_picker.rs | 99 +++++++++++++----- crates/ui-egui/src/dialogs/script_run.rs | 26 ++++- crates/ui-egui/src/script_runs.rs | 17 +++- crates/ui-egui/src/tests/script_dialogs.rs | 107 +++++++++++++++++++- docs/mcp.md | 18 +++- docs/target-app-parity.md | 1 + 11 files changed, 425 insertions(+), 53 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 2640433606..56bf96195f 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | a color as paint.setFill takes it, or null (colorPicker)}] (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; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK in a CMYK document), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"} or {kind: \"colorPicker\", color, answer: a color | null | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index a674396f4b..afda864f6a 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -5,12 +5,14 @@ //! it is left out or `undefined` ([`DEFAULT_TITLE`]), and `errorIcon` and `noAsDflt` as the //! boolean `Boolean(value)` gives. `alert` returns `undefined`, `confirm` `true` for Yes and //! `false` for No, and `prompt` the text in its field for OK and `null` for Cancel. +//! `app.showColorPicker(color)` ([`show_color_picker`]) opens the Color Picker on a color and +//! returns the color picked for OK, or a new object of the color it was given for Cancel. //! //! In the app the run waits at the call for the person's answer, and spends no fuel while it -//! waits; every dialog also has Stop, which ends the run and puts everything back. A run with -//! nobody to ask takes its answers, in order, from `script.run`'s `answers`; a call with no -//! answer left, or with the next answer for another kind of dialog, ends the run. The report's -//! `dialogs` lists each dialog and its answer. +//! waits; every dialog but the Color Picker also has Stop, which ends the run and puts +//! everything back. A run with nobody to ask takes its answers, in order, from `script.run`'s +//! `answers`; a call with no answer left, or with the next answer for another kind of dialog, +//! ends the run. The report's `dialogs` lists each dialog and its answer. //! //! The values here are VectorCraft's own limits: [`MAX_MESSAGE_BYTES`], [`MAX_TITLE_BYTES`], //! [`MAX_PROMPT_BYTES`], [`MAX_ANSWERS`], [`MAX_ANSWERS_BYTES`], [`MAX_RECORDS`] and @@ -21,6 +23,7 @@ use std::collections::VecDeque; use std::rc::Rc; use serde_json::{Map, Value, json}; +use vectorcraft_color::Color; use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError}; use super::{Host, console}; @@ -48,21 +51,33 @@ pub enum DialogKind { Alert, Confirm, Prompt, + /// `app.showColorPicker`. + ColorPicker, } impl DialogKind { - /// The function's name, which is also the `kind` of an answer and of a report's dialog. + /// The `kind` of an answer and of a report's dialog, which is also the function's name for + /// `alert`, `confirm` and `prompt`. pub fn id(self) -> &'static str { match self { Self::Alert => "alert", Self::Confirm => "confirm", Self::Prompt => "prompt", + Self::ColorPicker => "colorPicker", + } + } + + /// The function's name, as its errors give it. + fn function(self) -> &'static str { + match self { + Self::ColorPicker => "showColorPicker", + k => k.id(), } } } /// A dialog a script opened, which waits for its answer. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq)] pub struct ScriptDialog { pub kind: DialogKind, pub message: String, @@ -74,10 +89,12 @@ pub struct ScriptDialog { pub no_as_default: bool, /// `prompt`: the text its field starts with. pub preset: String, + /// `showColorPicker`: the color the picker starts with. `None` for the other dialogs. + pub color: Option, } /// The answer to a [`ScriptDialog`]. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq)] pub enum DialogAnswer { /// OK, for `alert`. Ok, @@ -85,6 +102,8 @@ pub enum DialogAnswer { Confirm(bool), /// OK with the field's text, or Cancel (`None`), for `prompt`. Prompt(Option), + /// OK with the color picked, or Cancel (`None`), for `showColorPicker`. + ColorPicker(Option), } impl DialogAnswer { @@ -93,29 +112,51 @@ impl DialogAnswer { Self::Ok => DialogKind::Alert, Self::Confirm(_) => DialogKind::Confirm, Self::Prompt(_) => DialogKind::Prompt, + Self::ColorPicker(_) => DialogKind::ColorPicker, } } - /// What the function returns. - fn data(&self) -> Data { + /// What the function returns for dialog `d`: for Cancel in the Color Picker, the color it + /// started with. + fn data(&self, d: &ScriptDialog) -> Data { match self { Self::Ok => Data::Undefined, Self::Confirm(b) => Data::Bool(*b), Self::Prompt(Some(t)) => Data::String(t.clone()), Self::Prompt(None) => Data::Null, + Self::ColorPicker(picked) => picked.or(d.color).as_ref().map_or(Data::Null, super::dom::color_data), } } - /// The answer as a report gives it: `"ok"`, a boolean, a string or `null`. + /// The answer as a report gives it: `"ok"`, a boolean, a string, a color as the paint commands + /// take it, or `null`. fn json(&self) -> Value { match self { Self::Ok => json!("ok"), Self::Confirm(b) => json!(b), Self::Prompt(t) => json!(t), + Self::ColorPicker(c) => c.as_ref().map_or(Value::Null, color_json), } } } +/// `c` as the paint commands take it. +fn color_json(c: &Color) -> Value { + serde_json::to_value(c).unwrap_or(Value::Null) +} + +/// Are `c`'s components in their ranges: 0 to 1, and for Lab, L from 0 to 100 and a and b from +/// -128 to 128, as a script's `LabColor` takes them? +fn in_range(c: &Color) -> bool { + let unit = |v: &[f32]| v.iter().all(|x| (0.0..=1.0).contains(x)); + match *c { + Color::Rgb { r, g, b } => unit(&[r, g, b]), + Color::Cmyk { c, m, y, k } => unit(&[c, m, y, k]), + Color::Gray { k } => unit(&[k]), + Color::Lab { l, a, b } => (0.0..=100.0).contains(&l) && [a, b].iter().all(|x| (-128.0..=128.0).contains(x)), + } +} + /// `text` as a dialog shows it. With `lines`, a line feed, a carriage return or the two together /// is a line break; every other control character, and with `lines` false every line break too, /// shows as its Unicode Control Picture, as the Script Console shows it. @@ -148,7 +189,8 @@ pub fn cut_to(text: &str, max: usize) -> &str { } /// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value: -/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter +/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "colorPicker", value: color | +/// null}`, the color in any form the paint commands take. An empty object, which the parameter /// took before dialogs existed, is an empty list. pub(crate) fn parse_answers(v: Option<&Value>) -> Result, String> { let list = match v { @@ -180,7 +222,12 @@ fn answer(a: &Value) -> Result { (Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))), (Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"), (Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"), - _ => Err("must have `kind` alert, confirm or prompt"), + (Some("colorPicker"), Value::Null) => Ok(DialogAnswer::ColorPicker(None)), + (Some("colorPicker"), v) => match crate::cmd::color_value(v).filter(in_range) { + Some(c) => Ok(DialogAnswer::ColorPicker(Some(c))), + None => Err("is a color picker's answer, whose `value` must be a color or null"), + }, + _ => Err("must have `kind` alert, confirm, prompt or colorPicker"), } } @@ -245,8 +292,9 @@ impl Dialogs { 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()); + let data = answer.data(d); *waiting = None; - if let Err(e) = realm.answer(answer.data()) { + if let Err(e) = realm.answer(data) { *self.failed.borrow_mut() = Some(e); } true @@ -263,12 +311,15 @@ impl Dialogs { self.count.set(self.count.get().saturating_add(1)); let mut r = Map::new(); r.insert("kind".into(), json!(d.kind.id())); - r.insert("message".into(), json!(d.message)); - r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE))); + if d.kind != DialogKind::ColorPicker { + r.insert("message".into(), json!(d.message)); + r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE))); + } match d.kind { DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)), DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)), DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)), + DialogKind::ColorPicker => r.insert("color".into(), d.color.as_ref().map_or(Value::Null, color_json)), }; r.insert("answer".into(), answer); let r = Value::Object(r); @@ -319,7 +370,8 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result host.charge_call(args.iter().map(super::data_size).sum())?; let Some(message) = text(args, 0) else { return Err(HostError::Type(format!("{name}: give a message"))) }; let (title, error_icon, no_as_default, preset) = match kind { - DialogKind::Alert => (text(args, 1), flag(args, 2), false, String::new()), + // `showColorPicker` opens through `show_color_picker`, not here. + DialogKind::Alert | DialogKind::ColorPicker => (text(args, 1), flag(args, 2), false, String::new()), DialogKind::Confirm => (text(args, 2), false, flag(args, 1), String::new()), DialogKind::Prompt => { let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) }; @@ -335,7 +387,29 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result if preset.len() > MAX_PROMPT_BYTES { return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB"))); } - let dialog = ScriptDialog { kind, message, title, error_icon, no_as_default, preset }; + wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None }) +} + +/// `app.showColorPicker(color)`: the Color Picker on `color`. It returns the color picked for OK, +/// and a new object of `color` for Cancel. +pub(super) fn show_color_picker(host: &Host, color: Color) -> Result { + let dialog = ScriptDialog { + kind: DialogKind::ColorPicker, + message: String::new(), + title: None, + error_icon: false, + no_as_default: false, + preset: String::new(), + color: Some(color), + }; + wait_or_answer(host, dialog) +} + +/// Opens `dialog`: in the app the run waits at it, and a run with nobody to ask takes the next of +/// `answers`. +fn wait_or_answer(host: &Host, dialog: ScriptDialog) -> Result { + let kind = dialog.kind; + let name = kind.function(); let d = &host.dialogs; if d.framed { if !d.can_wait.get() { @@ -350,11 +424,11 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result match next { Some(a) if a.kind() == kind => { d.record(&dialog, a.json()); - Ok(a.data()) + Ok(a.data(&dialog)) } Some(a) => { d.record(&dialog, json!("missing")); - Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {name}", a.kind().id()))) + Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {}", a.kind().id(), kind.id()))) } None => { d.record(&dialog, json!("missing")); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8b2267a5d8..0a7eb82ef5 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -41,6 +41,8 @@ use crate::{DocState, Document, NodeId, NodeKind, Session}; mod colors; mod paths; +pub(super) use colors::of_color as color_data; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -691,6 +693,13 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } +/// `app.showColorPicker(color)`: the Color Picker on `color`, which must be an `RGBColor`, +/// `CMYKColor`, `GrayColor` or `LabColor` ([`super::dialogs::show_color_picker`]). +fn app_show_color_picker(h: &Host, a: &[Data]) -> Answer { + let color = colors::solid(arg(a, 1), "showColorPicker's color")?; + super::dialogs::show_color_picker(h, color) +} + /// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter /// or a `\`) letters in one case. fn path_key(p: &str) -> String { @@ -1883,6 +1892,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("selection", get(l, app_selection)), ("coordinateSystem", property(l, app_coords, app_set_coords)), ("getIsFileOpen", method(l, app_is_open)), + ("showColorPicker", method(l, app_show_color_picker)), ]); application.push(later(l, "Application", "beep")); let preset = { diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index 34c1496054..da34e8cf31 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -66,7 +66,7 @@ fn shown(v: f32, scale: f64) -> f64 { } /// The color object for a solid color. -fn of_color(c: &Color) -> Data { +pub(in crate::script) fn of_color(c: &Color) -> Data { match *c { Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]), Color::Cmyk { c, m, y, k } => color_object( @@ -131,6 +131,18 @@ pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result std::result::Result { + let not_solid = || HostError::Type(format!("{what} must be an RGBColor, CMYKColor, GrayColor or LabColor")); + match assigned(d, what) { + Ok(Some(c)) => Ok(c), + // A NoColor, or one of the LATER classes, which `assigned` refuses with a plain error. + Ok(None) | Err(HostError::Error(_)) => Err(not_solid()), + Err(e) => Err(e), + } +} + /// `color` as `paint.setFill` and `paint.setStroke` take it. pub(super) fn param(color: &Color) -> Value { serde_json::to_value(color).unwrap_or(Value::Null) diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index baa8989208..aa373d09bb 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -177,6 +177,7 @@ fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() { error_icon: false, no_as_default: true, preset: String::new(), + color: None, }; assert_eq!(s.script_dialog(), Some(want)); assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); @@ -319,3 +320,74 @@ fn a_dialog_in_a_callback_throws_in_the_app() { assert!(r["log"][0].as_str().unwrap().contains("callback"), "{r}"); assert_eq!(r["dialogCount"], 0); } + +/// `showColorPicker` with an RGB red, the answer, and the run's log line for the color it returns. +const PICK_RED: &str = "var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join());"; + +#[test] +fn a_run_with_nobody_to_ask_takes_the_picked_color_from_answers() { + let mut s = one_doc(); + let source = format!("{PICK_RED} var g = new GrayColor(); g.gray = 40; var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join());"); + let r = headless(&mut s, &source, answers(&[json!({"kind": "colorPicker", "value": "#00FF00"}), json!({"kind": "colorPicker", "value": null})])) + .unwrap(); + assert_eq!(r["log"], json!(["RGBColor,0,255,0", "GrayColor,40"]), "OK gives the picked color, Cancel the color given: {r}"); + let dialogs = r["dialogs"].as_array().unwrap(); + assert_eq!(dialogs.len(), 2); + assert!(dialogs.iter().all(|d| d["kind"] == "colorPicker" && d["color"].is_object() && d.get("message").is_none()), "{r}"); + assert_eq!(dialogs[1]["answer"], Value::Null, "Cancel is listed as null"); + let cmyk = headless( + &mut s, + "var c = new CMYKColor(); c.cyan = 20; vc.log(app.showColorPicker(c).typename);", + answers(&[json!({"kind": "colorPicker", "value": {"c": 0, "m": 100, "y": 100, "k": 0}})]), + ) + .unwrap(); + assert_eq!(cmyk["log"], json!(["CMYKColor"]), "the picked color keeps its own model: {cmyk}"); +} + +#[test] +fn the_color_picker_ends_the_run_when_no_answer_is_left() { + let mut s = one_doc(); + let before = art(&s); + let edit = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});"; + for (given, says) in [(json!([]), "no answer left"), (answers(&[json!({"kind": "prompt", "value": "x"})]), "is for prompt, not colorPicker")] { + let source = format!("{edit} try {{ {PICK_RED} }} catch (e) {{ vc.log('caught'); }}"); + let e = headless(&mut s, &source, given).unwrap_err().to_string(); + assert!(e.contains("showColorPicker") && e.contains(says), "{e}"); + assert_eq!(art(&s), before, "the run's edit goes back"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!([]), "a missing answer cannot be caught"); + assert_eq!(report["dialogs"][0]["answer"], "missing", "{report}"); + } + let a = headless(&mut s, "alert('x');", answers(&[json!({"kind": "colorPicker", "value": null})])).unwrap_err().to_string(); + assert!(a.contains("is for colorPicker, not alert"), "{a}"); +} + +#[test] +fn the_color_picker_refuses_what_is_not_a_solid_color() { + let mut s = one_doc(); + let source = "var out = []; [undefined, 'red', new NoColor(), {typename: 'SpotColor', tint: 100}].forEach(function (c) {\ + try { app.showColorPicker(c); out.push('opened'); } catch (e) { out.push(e.name); } });\ + try { var big = new RGBColor(); big.red = 300; app.showColorPicker(big); } catch (e) { out.push(e.name); } vc.log(out.join());"; + let r = headless(&mut s, source, json!([])).unwrap(); + assert_eq!(r["log"], json!(["TypeError,TypeError,TypeError,TypeError,RangeError"]), "{r}"); + assert_eq!(r["dialogCount"], 0, "no picker opened"); + for bad in [json!("not a color"), json!([255, 0, 0]), json!({"model": "lab", "l": 120, "a": 0, "b": 0}), json!(true)] { + let e = headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": bad})])).unwrap_err().to_string(); + assert!(e.contains("color picker's answer"), "{bad}: {e}"); + } +} + +#[test] +fn a_framed_run_waits_at_the_color_picker() { + let mut s = one_doc(); + framed(&mut s, &format!("{PICK_RED} var q = app.showColorPicker(p); vc.log(q.green);")); + let d = s.script_dialog().unwrap(); + assert_eq!((d.kind, d.color), (DialogKind::ColorPicker, Some(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))); + assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); + assert!(s.script_answer(DialogAnswer::ColorPicker(Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))))); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_dialog().unwrap().color, Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)), "it opens on the color it is given"); + assert!(s.script_answer(DialogAnswer::ColorPicker(None))); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!(["RGBColor,0,0,255", 0]), "{r}"); +} diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index af1b318728..4060b26d40 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -27,6 +27,7 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::ColorMode; use vectorcraft_engine::cmd::color_value; use vectorcraft_engine::cmd::swatchlib; +use vectorcraft_engine::script::DialogAnswer; use super::preview::LivePreview; use crate::panels::color::{WorkingRgb, color_of_values, gamut, model_values}; @@ -45,6 +46,8 @@ pub(crate) enum Target { Artboard(usize), /// A colour row `key` of the open dialog `parent`. Answer { parent: DialogId, key: String }, + /// The answer to a running script's `app.showColorPicker`, which opened it on this colour. + Script(Color), } /// One open Color Picker: what the dialog itself does not know. @@ -152,28 +155,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { }; let dialogs = app.dialogs().ok_or("no window")?; let start = srgba(&color); - let mut dialog = ColorPickerDialog::new( - match (artboard, stroke) { - (Some(_), _) => "artboard", - (None, true) => "stroke", - (None, false) => "fill", - }, - tl!("Color Picker"), - start, - ) - .eyedropper(true) - .add_to_swatches(false) - .gamut(gamut(app)) - .working_rgb(WorkingRgb) - .swatch_view(swatch_view(app)); - if app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) - && let Some(converter) = working_cmyk() - { - dialog = dialog.cmyk(&converter); - } - if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { - dialog = dialog.kept(model_values(&color)); - } + let key = match (artboard, stroke) { + (Some(_), _) => "artboard", + (None, true) => "stroke", + (None, false) => "fill", + }; + let mut dialog = picker(app, key, &color); // PLAN: assumed the dialog's own `instance` keeps artboards apart; the host replaces a picker only for the same target. if let Some((i, _)) = artboard { dialog = dialog.instance(i); @@ -196,6 +183,58 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } +/// The Color Picker with `key` on `color`, with the eyedropper, the gamut warning, the document's +/// swatches and libraries, and in a CMYK document the working CMYK inks. +fn picker(app: &VectorcraftApp, key: &str, color: &Color) -> ColorPickerDialog { + let mut dialog = ColorPickerDialog::new(key, tl!("Color Picker"), srgba(color)) + .eyedropper(true) + .add_to_swatches(false) + .gamut(gamut(app)) + .working_rgb(WorkingRgb) + .swatch_view(swatch_view(app)); + if app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) + && let Some(converter) = working_cmyk() + { + dialog = dialog.cmyk(&converter); + } + if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { + dialog = dialog.kept(model_values(color)); + } + dialog +} + +/// Opens the Color Picker a running script's `app.showColorPicker` waits at, on `color`. It +/// previews nothing; its OK and Cancel answer the run ([`finish`]). +pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color) { + let Some(dialogs) = app.dialogs() else { return }; + // The given colour's own values, so that OK can tell an untouched pick from another model's. + let dialog = picker(app, SCRIPT_KEY, &color).kept(model_values(&color)); + let id = dialogs.with(|h| h.open(dialog)); + app.color_dialogs.pickers.retain(|o| o.id != id); + app.color_dialogs.pickers.push(Open { id, target: Target::Script(color), start: srgba(&color), keep: false, preview: LivePreview::default() }); +} + +/// The key of the Color Picker a script opens. +pub(crate) const SCRIPT_KEY: &str = "script"; + +/// The id of the Color Picker a running script waits at, while it is open or its answer is not +/// yet given. +pub(crate) fn script_picker(app: &VectorcraftApp) -> Option { + app.color_dialogs.pickers.iter().find(|o| matches!(o.target, Target::Script(_))).map(|o| o.id) +} + +/// Closes the script's Color Picker once the run no longer waits at it, and drops its answer. +pub(crate) fn forget_script(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(id) = script_picker(app) else { return }; + app.color_dialogs.pickers.retain(|o| o.id != id); + if let Some(dialogs) = app.dialogs() { + dialogs.with(|h| { + h.cancel_by_id(ctx, id); + let _ = h.take_by_id::(id); + }); + } +} + /// Once per frame (after the shell pass): opens a picker for each dialog's colour request, previews /// each open picker's colour on the art, hands it the screen picks, and settles the ones that /// closed. @@ -259,6 +298,15 @@ fn finish( dialogs.with(|h| h.answer_color(*parent, key, r.picked.color)); } } + // OK on the colour it opened with, in the model it opened with, gives that colour back. + (Some(DialogResult::Ok(r)), Target::Script(given)) => { + let untouched = r.picked.color == open.start && r.picked.model == Some(model_values(given)); + let picked = if untouched { *given } else { in_document_model(app, color_of(&r.picked)) }; + app.session.script_answer(DialogAnswer::ColorPicker(Some(picked))); + } + (_, Target::Script(_)) => { + app.session.script_answer(DialogAnswer::ColorPicker(None)); + } (Some(DialogResult::Ok(r)), _) => { if let Err(e) = commit(app, open, preview, &r.picked) { app.status(e); @@ -273,7 +321,7 @@ fn paint_command(target: &Target, c: Color) -> (&'static str, Value) { match target { Target::Artboard(i) => ("artboard.setProps", json!({ "index": i, "color": color_json(&c) })), Target::Stroke => ("paint.setStroke", json!({ "color": color_json(&c) })), - Target::Fill | Target::Answer { .. } => ("paint.setFill", json!({ "color": color_json(&c) })), + Target::Fill | Target::Answer { .. } | Target::Script(_) => ("paint.setFill", json!({ "color": color_json(&c) })), } } @@ -291,8 +339,9 @@ fn in_document_model(app: &VectorcraftApp, c: Color) -> Color { /// preview. Nothing previews until the colour first changes, nor without a selection (the colour /// then only becomes the default paint, on OK). An artboard shows it with or without a selection. fn preview(app: &mut VectorcraftApp, open: &mut Open, picked: &PickedColor) { - // A picker over a command dialog only fills a row; the dialog previews it. - if matches!(open.target, Target::Answer { .. }) { + // A picker over a command dialog only fills a row; the dialog previews it. A script's picker + // only answers the script. + if matches!(open.target, Target::Answer { .. } | Target::Script(_)) { return; } let (cmd, params) = paint_command(&open.target, in_document_model(app, color_of(picked))); diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index ae13009775..65b7c92e1a 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -29,6 +29,7 @@ use std::path::Path; +use craft::color_ui::ui::ColorPickerDialog; use craft::host::{PickRequest, Picked}; use craft::theme::variant::Tone; use craft::ui::buttons::Button; @@ -46,6 +47,7 @@ use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog}; +use super::color_picker; use crate::VectorcraftApp; use crate::file_asks::{self, Owner}; @@ -430,6 +432,22 @@ pub(crate) fn forget(app: &VectorcraftApp) { }); } +/// [`forget`] for the Color Picker a script's `app.showColorPicker` opened. +pub(crate) fn forget_color_picker(app: &mut VectorcraftApp) { + let Some(ctx) = app.ui_ctx.clone() else { return }; + if color_picker::script_picker(app).is_none() { + return; + } + let asking = with_host(app, |host, _| host.is_open::()).unwrap_or(false); + color_picker::forget_script(app, &ctx); + if asking { + with_host(app, |host, _| { + let _ = host.take::(); + host.open(close_question()); + }); + } +} + /// `ui.runScript`: the script at `path` or given as `source`; without either, pick a file. pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result { if p.get("path").is_some() || p.get("source").is_some() { @@ -514,8 +532,13 @@ pub(crate) fn open_picker(app: &VectorcraftApp, p: ScriptPicker) { /// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which /// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet. pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { + let picker = color_picker::script_picker(app); with_host(app, |host, _| { - let own = host.get::().map(StackDialog::id).or_else(|| host.get::().map(StackDialog::id)); + let own = host + .get::() + .map(StackDialog::id) + .or_else(|| host.get::().map(StackDialog::id)) + .or_else(|| picker.filter(|&id| host.get_by_id::(id).is_some())); match own { Some(parent) if host.stack().is_top(parent) => { host.open_child(close_question(), parent); @@ -585,6 +608,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { crate::script_runs::failed(app, error); forget::(app); forget::(app); + forget_color_picker(app); app.sync_views(); } if with_host(app, |host, _| host.get_mut::().is_some_and(|d| std::mem::take(&mut d.choose))).unwrap_or(false) { diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index b08a8f2e93..e4f6303fab 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -1,9 +1,13 @@ //! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with -//! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer. +//! `alert`, `confirm`, `prompt`, `app.showColorPicker` or a `File` or `Folder` file dialog, waits +//! for the person's answer. + +use vectorcraft_engine::script::DialogKind; use crate::VectorcraftApp; +use crate::dialogs::color_picker; use crate::dialogs::script_run::{self, GrowthQuestion, ScriptFiles, ScriptNotice}; /// Advances the running script by one slice, or asks what its growth needs asked. @@ -47,13 +51,22 @@ fn ask(app: &mut VectorcraftApp) -> bool { } script_run::forget::(app); if let Some(dialog) = app.session.script_dialog() { - if !script_run::busy(app) { + if dialog.kind == DialogKind::ColorPicker { + // A picker that closed this frame answers the run in its own pump. + if color_picker::script_picker(app).is_none() + && !script_run::busy(app) + && let Some(color) = dialog.color + { + color_picker::open_for_script(app, color); + } + } else if !script_run::busy(app) { script_run::open_notice(app, &dialog); } return true; } // A run asked to stop no longer waits at its dialog. script_run::forget::(app); + script_run::forget_color_picker(app); if app.session.script_waiting() { if !script_run::busy(app) { script_run::open_growth(app); diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs index 94e1bb9311..3417c5580b 100644 --- a/crates/ui-egui/src/tests/script_dialogs.rs +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -1,12 +1,14 @@ //! A script's `alert`, `confirm` and `prompt` in the app: the dialog the run waits at, its buttons, //! Enter and Escape, Stop, another dialog in the way, quitting while it waits, and the same answers -//! given by a run with nobody to ask. The helpers over the dialog host are shared with the other -//! script tests. +//! given by a run with nobody to ask; and the Color Picker of `app.showColorPicker`. The helpers +//! over the dialog host are shared with the other script tests. +use craft::color_ui::ui::{ColorPickerDialog, PickedColor}; use craft::ui::dialog::{DialogId, StackDialog, StandardPrompt}; use serde_json::{Value, json}; use vectorcraft_engine::Session; +use crate::dialogs::color_picker; use crate::dialogs::script_run::{self, CLOSE_KIND, CloseQuestion, NOTICE_KIND, ScriptNotice}; use crate::{VectorcraftApp, menus, script_runs}; @@ -315,3 +317,104 @@ fn the_app_and_a_run_with_nobody_to_ask_give_the_same_results() { assert_eq!(framed["dialogs"], headless["dialogs"]); assert_eq!(framed["log"], json!([true, "p", "done"])); } + +/// Is the Color Picker of the script's `app.showColorPicker` open? +fn picker_open(app: &VectorcraftApp) -> bool { + let id = color_picker::script_picker(app); + id.is_some_and(|id| script_run::with_host(app, |host, _| host.get_by_id::(id).is_some()).unwrap()) +} + +/// Polls the run until it ends, or until its Color Picker is open (true). +fn until_picker(app: &mut VectorcraftApp) -> bool { + for _ in 0..10_000 { + if !app.session.script_running() { + return false; + } + script_runs::poll(app); + if picker_open(app) { + return true; + } + } + panic!("the script neither ended nor opened the Color Picker"); +} + +/// Answers the script's Color Picker with OK (or Cancel), then runs the frame's picker pump. +fn answer_picker(app: &mut VectorcraftApp, ok: bool) { + let id = color_picker::script_picker(app).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let done = script_run::with_host(app, |host, ctx| if ok { host.confirm_by_id(ctx, id) } else { host.cancel_by_id(ctx, id) }).unwrap(); + assert!(done); + color_picker::pump(app, &ctx); +} + +#[test] +fn the_color_picker_waits_and_answers_the_run() { + let mut app = app(); + let gray = "var g = new GrayColor(); g.gray = 40;"; + start( + &mut app, + &format!( + "{DRAW} var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join()); \ + {gray} var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join()); var r = app.showColorPicker(g); vc.log([r.typename, r.gray].join());" + ), + ); + assert!(until_picker(&mut app)); + assert!(!is_open::(&app), "the picker opens in place of a notice"); + set(&app, color_picker::SCRIPT_KEY, "color", json!("#00ff00")).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + color_picker::pump(&mut app, &ctx); + assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "the selection shows no preview"); + answer_picker(&mut app, true); + assert!(until_picker(&mut app), "the next call opens the picker again"); + answer_picker(&mut app, true); + assert!(until_picker(&mut app)); + answer_picker(&mut app, false); + assert!(!until_picker(&mut app)); + assert_eq!( + log(&app), + json!(["RGBColor,0,255,0", "GrayColor,40", "GrayColor,40"]), + "OK gives the color picked, untouched its own color, Cancel the color given" + ); + assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "OK paints nothing"); + let dialogs = app.session.script_report().unwrap()["dialogs"].clone(); + assert_eq!(dialogs[2]["answer"], Value::Null, "Cancel is listed as null"); +} + +#[test] +fn the_same_color_set_in_another_model_is_a_new_pick() { + let mut app = app(); + start(&mut app, "var g = new GrayColor(); g.gray = 40; var p = app.showColorPicker(g); vc.log(p.typename);"); + assert!(until_picker(&mut app)); + // The gray's own sRGB, set as a plain color, as a screen sample sets one. + let open = app.color_dialogs.pickers.iter().find(|o| Some(o.id) == color_picker::script_picker(&app)).map(|o| (o.id, o.start)).unwrap(); + script_run::with_host(&app, |host, _| host.get_mut_by_id::(open.0).map(|d| d.set_color(PickedColor::rgb(open.1)))).unwrap(); + answer_picker(&mut app, true); + assert!(!until_picker(&mut app)); + assert_eq!(log(&app), json!(["RGBColor"]), "the same sRGB as a plain color is an RGB pick, not the gray the script gave"); +} + +#[test] +fn stopping_or_quitting_the_run_closes_its_color_picker() { + let source = format!("{DRAW} var c = new RGBColor(); app.showColorPicker(c); vc.log('after');"); + let mut app = app(); + start(&mut app, &source); + assert!(until_picker(&mut app)); + assert_eq!(app.run("script.stop", json!({})).unwrap()["stopped"], true); + assert!(!until_picker(&mut app)); + assert!(!picker_open(&app), "no picker is left for the stopped run"); + assert!(color_picker::script_picker(&app).is_none()); + assert_eq!(objects(&app), 0, "the run's edit goes back"); + assert_eq!(log(&app), json!([])); + let mut app = self::app(); + start(&mut app, &source); + assert!(until_picker(&mut app)); + script_run::ask_to_close(&mut app); + assert!(is_open::(&app), "quitting asks over the picker"); + cancel(&mut app, CLOSE_KIND); + assert!(picker_open(&app), "Cancel shows the picker again"); + script_run::ask_to_close(&mut app); + assert!(confirm(&mut app, CLOSE_KIND)); + assert!(!app.session.script_running()); + assert!(!picker_open(&app), "no picker is left for the abandoned run"); + assert_eq!(objects(&app), 0); +} diff --git a/docs/mcp.md b/docs/mcp.md index da2ab72029..5321b74f87 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2667,7 +2667,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.log(value)` adds a value to the report and a line to the Script Console. - `app` is the application object the help page https://ai-scripting.docsforadobe.dev/jsobjref/Application/ describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one), - `app.selection`, `app.coordinateSystem` and `app.getIsFileOpen(path)`. `app.documents` + `app.selection`, `app.coordinateSystem`, `app.getIsFileOpen(path)` and `app.showColorPicker(color)`, described + with the dialogs below. `app.documents` (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of @@ -3048,7 +3049,9 @@ app's own errors, syntax errors and limits. The status bar shows a `script` mess - `dialogs` lists the run's dialogs in the order they opened, as `{kind, message, title, errorIcon, answer}` for `alert`, `{kind, message, title, noAsDefault, answer}` for `confirm` and `{kind, message, title, preset, answer}` for `prompt`. `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, `"stop"` for a dialog the - run ended at, or `"missing"` for a dialog `answers` had no answer for. `dialogCount` counts every dialog, and + run ended at, or `"missing"` for a dialog `answers` had no answer for. `app.showColorPicker` is listed as `{kind: + "colorPicker", color, answer}`, with the color it opened on and the color picked, `null` for Cancel or + `"missing"`, each color as `paint.setFill` takes it. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list stopped at its limit. ```json @@ -3096,6 +3099,17 @@ left, when the next answer is for another kind of dialog, or when the script end and refuses any answers for a run in the app, where the person answers. An omitted `answers`, an empty list and an empty object are the same. +`app.showColorPicker(color)` opens the Color Picker on `color` and returns a color, as the type definitions at +https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it. `color` must be an `RGBColor`, +`CMYKColor`, `GrayColor` or `LabColor`; anything else throws a `TypeError`, and a component out of its range throws a +`RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; in a CMYK +document an RGB pick is returned as CMYK. OK with the color unchanged and Cancel return a new object of the color the +script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting +end the run as they do at the other dialogs, and close the picker. A run with nobody to ask takes `{kind: +"colorPicker", value: color}` from `answers`, with the color in any form `paint.setFill` takes, each component in its +range, or `{kind: "colorPicker", value: null}` for Cancel. In the app, the picker's dialog key is `script`, and +`ui.dialog.set` and `ui.dialog.confirm` answer it as they answer any Color Picker. + ```sh vectorcraft-cli run --cmd script.run --params '{"source": "if (confirm(\"Add a frame?\")) vc.log(prompt(\"Name\", \"Frame\"));", "answers": [{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "Border"}]}' ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ff2ebf0bf4..864cff266f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1036,6 +1036,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: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.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`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, and Cancel a new object of the color given. A run with nobody to ask takes the pick from `answers` (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.