Browse… buttons in a script's own dialogs and panels open the file dialog instead of doing nothing (#3253)

* Scripts: a ScriptUI Browse… button opens the file dialog

Fixes #2778.
Fixes #2894.

File.openDialog, File.saveDialog, Folder.selectDialog and the instance
openDlg / saveDlg / selectDlg were stubs that returned null, so a script
dialog's or a dockable ScriptUI panel's Browse… button did nothing.

On a script-host thread, in an app that shows them, the script now asks
for the dialog (Session::script_ui.file_dialogs, each with an id), hands
the session back like a modal dialog's show() does and waits for the
answer: a File (an array with multiSelect), a Folder, or null when
cancelled. The script's filter becomes the dialog's (its name, "All Files"
for *.*); without extensions every file shows. Headless runs, the Script
Console, the web and Shutdown scripts get null at once.

The app shows the dialog after the pass's events: blocking on Windows
(Hooks::pick_file_dialog), without blocking on macOS and Linux, one at a
time; a non-blocking dialog that ends without answering counts as
cancelled. scriptui.fileDialogs lists the waiting dialogs and
scriptui.fileDialog answers one (refused while file access is confined,
and refused to scripts). A dialog leaves the list only when its script
has the answer; the script's windows refuse events meanwhile, except
scriptui.close, which cancels the file dialog first. A script host that
ends takes its dialogs with it.

* Scripts: carry a file dialog's prompt, start location and filter to the native dialog (#2778)

serve_file_dialogs collected the script's prompt, start folder and save filter
but dropped them at the host boundary. FileDialog::Script now carries prompt and
start, and new ScriptFolder and ScriptSave requests carry the folder dialog's
prompt/start and the save dialog's prompt and whole filter (label, extensions,
any file) instead of the default name's extension. Both the blocking and the
non-blocking host dialogs apply title, initial directory and filters; Save also
goes through the blocking hook where one is set. Hook-level regression test
asserts all three requests.

* Scripts: a hidden window paints so a script's file dialog is shown (#3253 review)

* Scripts: formatting (#3253)
This commit is contained in:
Valentin Klein authored and GitHub committed 2026-11-22 12:58:56 -06:00
1 parent e7bc3ad808
commit 525dcfc0d8
20 files changed
+945 -34

No files matched your search

+149 -5
View File
@@ -111,7 +111,9 @@ pub fn install_pickers(app: &mut EffectcraftApp, ctx: &egui::Context) -> Receive
let tx = Errors { tx, ctx: ctx.clone() };
let errors = tx.clone();
app.hooks.pick_files = Some(Box::new(move |exts: &[&str]| {
blocking(&errors, "Open", || rfd::FileDialog::new().add_filter("Media", exts).pick_files()).unwrap_or_default().into_iter().map(path_string).collect()
// No extensions (a script's File.openDialog without a filter): every file.
let dialog = || if exts.is_empty() { rfd::FileDialog::new() } else { rfd::FileDialog::new().add_filter("Media", exts) };
blocking(&errors, "Open", || dialog().pick_files()).unwrap_or_default().into_iter().map(path_string).collect()
}));
let errors = tx.clone();
app.hooks.pick_save = Some(Box::new(move |name: &str| {
@@ -123,6 +125,12 @@ pub fn install_pickers(app: &mut EffectcraftApp, ctx: &egui::Context) -> Receive
}));
let errors = tx.clone();
app.hooks.pick_folder = Some(Box::new(move || blocking(&errors, "Choose Folder", || rfd::FileDialog::new().pick_folder()).map(path_string)));
let errors = tx.clone();
// Scripts' file dialogs where they block (Windows; see `install_file_dialogs` in main.rs).
app.hooks.pick_file_dialog = Some(Box::new(move |dialog: FileDialog| {
let what = title(&dialog);
blocking(&errors, what, || Some(pick_blocking(dialog))).unwrap_or_default()
}));
let errors = tx;
app.hooks.pick_save_file = Some(Box::new(move |name: &str, ext: &str| {
blocking(&errors, "Save", || {
@@ -170,9 +178,9 @@ pub fn show_asked(asked: &Receiver<Asked>, frame: &eframe::Frame, ctx: &egui::Co
/// The dialog's title, for errors.
fn title(dialog: &FileDialog) -> &'static str {
match dialog {
FileDialog::Open { .. } | FileDialog::OpenProject => "Open",
FileDialog::Folder => "Choose Folder",
FileDialog::Save { .. } => "Save",
FileDialog::Open { .. } | FileDialog::OpenProject | FileDialog::Script { .. } => "Open",
FileDialog::Folder | FileDialog::ScriptFolder { .. } => "Choose Folder",
FileDialog::Save { .. } | FileDialog::ScriptSave { .. } => "Save",
}
}
@@ -231,6 +239,101 @@ fn path(file: Option<FileHandle>) -> Vec<String> {
paths(file.map(|f| vec![f]))
}
/// The filters of a script's file dialog (#2778): its own, under the script's name for it (else
/// "Files"), then "All Files" when the script's filter offers every file. Without extensions, no
/// filter: every file. macOS takes all the filters' extensions together as the allowed types, so a
/// dialog that also offers every file gets no filter there.
macro_rules! script_filters {
($dialog:expr, $label:expr, $exts:expr, $any:expr) => {{
let (d, label, exts, any): (_, &str, &[String], bool) = ($dialog, $label, $exts, $any);
if exts.is_empty() || (any && cfg!(target_os = "macos")) {
d
} else {
let d = d.add_filter(if label.is_empty() { "Files" } else { label }, exts);
if any { d.add_filter("All Files", &["*"]) } else { d }
}
}};
}
/// The folder a script's dialog starts in: its `start` when that is a folder, else the folder
/// the file `start` names lives in; `None` when neither exists (the system's choice).
fn start_dir(start: &str) -> Option<std::path::PathBuf> {
if start.is_empty() {
return None;
}
let at = std::path::Path::new(start);
if at.is_dir() { Some(at.to_path_buf()) } else { at.parent().filter(|d| d.is_dir()).map(std::path::Path::to_path_buf) }
}
/// The filters of a script's save dialog: the script's own ([`script_filters!`]), else the
/// extension of the default name.
fn save_exts(exts: &[String], default: &str) -> Vec<String> {
if exts.is_empty() { std::path::Path::new(default).extension().map(|e| vec![e.to_string_lossy().to_string()]).unwrap_or_default() } else { exts.to_vec() }
}
/// A script's file dialog, blocking until it closes (`Hooks::pick_file_dialog`, Windows): its
/// paths, empty when cancelled. Runs inside [`guarded`] (see [`install_pickers`]).
fn pick_blocking(dialog: FileDialog) -> Vec<String> {
let all =
|files: Option<Vec<std::path::PathBuf>>| -> Vec<String> { files.unwrap_or_default().into_iter().map(|p| p.to_string_lossy().to_string()).collect() };
let one = |file: Option<std::path::PathBuf>| all(file.map(|f| vec![f]));
match dialog {
FileDialog::Script { label, exts, any, many, prompt, start } => {
let mut d = script_filters!(rfd::FileDialog::new(), &label, &exts, any);
if !prompt.is_empty() {
d = d.set_title(&prompt);
}
if let Some(dir) = start_dir(&start) {
d = d.set_directory(dir);
}
if many { all(d.pick_files()) } else { one(d.pick_file()) }
}
FileDialog::ScriptFolder { prompt, start } => {
let mut d = rfd::FileDialog::new();
if !prompt.is_empty() {
d = d.set_title(&prompt);
}
if let Some(dir) = start_dir(&start) {
d = d.set_directory(dir);
}
one(d.pick_folder())
}
FileDialog::ScriptSave { default, prompt, label, exts, any } => {
let at = std::path::Path::new(&default);
let name = at.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let mut d = script_filters!(rfd::FileDialog::new(), &label, &save_exts(&exts, &default), any);
if !prompt.is_empty() {
d = d.set_title(&prompt);
}
if let Some(dir) = start_dir(&default) {
d = d.set_directory(dir);
}
one(d.set_file_name(name).save_file())
}
FileDialog::Open { exts, many } => {
let d = if exts.is_empty() { rfd::FileDialog::new() } else { rfd::FileDialog::new().add_filter("Media", &exts) };
if many { all(d.pick_files()) } else { one(d.pick_file()) }
}
FileDialog::OpenProject => one(rfd::FileDialog::new().add_filter("EffectCraft Project", &["ecproj", "ecprojx"]).pick_file()),
FileDialog::Folder => one(rfd::FileDialog::new().pick_folder()),
FileDialog::Save { default, ext, project } => {
let at = std::path::Path::new(&default);
let name = at.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let mut d = if project {
rfd::FileDialog::new().add_filter("EffectCraft Project", &["ecproj"])
} else if ext.is_empty() {
rfd::FileDialog::new()
} else {
rfd::FileDialog::new().add_filter(&ext, &[ext.as_str()])
};
if let Some(dir) = at.parent().filter(|d| d.is_dir()) {
d = d.set_directory(dir);
}
one(d.set_file_name(name).save_file())
}
}
}
/// The dialog, as the blocking hooks show it. On macOS rfd makes the panel here, before the
/// future is returned, so a panel AppKit can't make panics here, inside [`guarded`].
///
@@ -242,7 +345,8 @@ fn path(file: Option<FileHandle>) -> Vec<String> {
fn open(dialog: FileDialog, frame: &eframe::Frame) -> Answer {
match dialog {
FileDialog::Open { exts, many } => {
let d = parented(frame).add_filter("Media", &exts);
// No extensions (a script's File.openDialog without a filter): every file.
let d = if exts.is_empty() { parented(frame) } else { parented(frame).add_filter("Media", &exts) };
if many {
let f = d.pick_files();
Box::pin(async move { paths(f.await) })
@@ -251,6 +355,46 @@ fn open(dialog: FileDialog, frame: &eframe::Frame) -> Answer {
Box::pin(async move { path(f.await) })
}
}
FileDialog::Script { label, exts, any, many, prompt, start } => {
let mut d = script_filters!(parented(frame), &label, &exts, any);
if !prompt.is_empty() {
d = d.set_title(&prompt);
}
if let Some(dir) = start_dir(&start) {
d = d.set_directory(dir);
}
if many {
let f = d.pick_files();
Box::pin(async move { paths(f.await) })
} else {
let f = d.pick_file();
Box::pin(async move { path(f.await) })
}
}
FileDialog::ScriptFolder { prompt, start } => {
let mut d = parented(frame);
if !prompt.is_empty() {
d = d.set_title(&prompt);
}
if let Some(dir) = start_dir(&start) {
d = d.set_directory(dir);
}
let f = d.pick_folder();
Box::pin(async move { path(f.await) })
}
FileDialog::ScriptSave { default, prompt, label, exts, any } => {
let at = std::path::Path::new(&default);
let name = at.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let mut d = script_filters!(parented(frame), &label, &save_exts(&exts, &default), any);
if !prompt.is_empty() {
d = d.set_title(&prompt);
}
if let Some(dir) = start_dir(&default) {
d = d.set_directory(dir);
}
let f = d.set_file_name(name).save_file();
Box::pin(async move { path(f.await) })
}
FileDialog::OpenProject => {
let f = parented(frame).add_filter("EffectCraft Project", &["ecproj", "ecprojx"]).pick_file();
Box::pin(async move { path(f.await) })
+2
View File
@@ -59,6 +59,8 @@ const REFUSED: &[&str] = &[
"scriptui.set",
"scriptui.mouse",
"scriptui.close",
// Hands a script the file it waits on, so its code goes on.
"scriptui.fileDialog",
"file.executeFile",
"effect.helpers.scan",
"effect.helpers.load",
+1
View File
@@ -1587,6 +1587,7 @@ fn automation_roots_refuse_running_script_code() {
("scriptui.set", json!({"window": 1, "widget": 2, "value": 1})),
("scriptui.mouse", json!({"window": 1, "widget": 2, "type": "click"})),
("scriptui.close", json!({"window": 1})),
("scriptui.fileDialog", json!({"host": 1, "paths": null})),
] {
let msg = refused(&mut s, "execute_command", json!({"command": command, "params": params}));
assert!(msg.contains("not available while file access is confined"), "`{command}`: {msg}");
+21 -1
View File
@@ -430,7 +430,12 @@ fn run_startup(s: &mut Session, _: &Value) -> Result<Value> {
/// (frontends call it as the app quits, after the unsaved-changes prompt).
fn run_shutdown(s: &mut Session, _: &Value) -> Result<Value> {
s.replace_project(effectcraft_project::Project::default(), None);
Ok(run_folder(s, SHUTDOWN_DIR, true))
// The app is quitting: nothing would show a Shutdown script's file dialog (File.saveDialog…),
// so it gets null at once instead of waiting.
let answers = std::mem::replace(&mut s.script_ui.answers_file_dialogs, false);
let r = run_folder(s, SHUTDOWN_DIR, true);
s.script_ui.answers_file_dialogs = answers;
Ok(r)
}
/// Window ▸ `<ScriptUI panel>`: run the panel script (or bring its panel forward).
@@ -599,6 +604,21 @@ pub fn specs() -> Vec<CommandSpec> {
always,
scriptui::close
),
crate::query!(
"scriptui.fileDialogs",
"Script File Dialogs",
"{} → [{id, host, kind: open|save|folder, prompt, exts, label, any, many, start, shown}]: the file dialogs scripts wait on (File.openDialog, File.saveDialog, Folder.selectDialog…)",
scriptui::file_dialogs
),
cmd!(
"scriptui.fileDialog",
"Answer Script File Dialog",
[],
None,
"{id? (from scriptui.fileDialogs; default the only one), host?, paths: [path…] | null (cancelled)} → the waiting script goes on with the picked files",
always,
scriptui::file_dialog
),
]
}
+104
View File
@@ -436,6 +436,50 @@ pub struct ScriptUiEvent {
/// The ScriptUI mouse events scripts can listen for (`addEventListener`).
pub const MOUSE_EVENTS: [&str; 6] = ["mousedown", "mouseup", "mousemove", "mouseover", "mouseout", "click"];
/// The [`ScriptUiEvent::kind`] that answers a script's file dialog ([`ScriptFileDialog`]); its
/// value is `{host, paths: [path…] | null}` and it goes to the script context `host`, not to a
/// window.
pub const FILE_DIALOG_EVENT: &str = "fileDialog";
/// What a script's file dialog picks.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FileDialogKind {
/// A file (or several) to open: `File.openDialog`, `file.openDlg`.
#[default]
Open,
/// Where to save: `File.saveDialog`, `file.saveDlg`.
Save,
/// A folder: `Folder.selectDialog`, `folder.selectDlg`.
Folder,
}
/// A file dialog a script asked for and waits on (#2778). The frontend shows it and answers with
/// `scriptui.fileDialog`; agents can answer it the same way.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct ScriptFileDialog {
/// Unique in the process: an answer goes to this dialog only.
pub id: u32,
/// The script context waiting for the answer.
pub host: u32,
pub kind: FileDialogKind,
/// The script's prompt.
pub prompt: String,
/// The extensions the script's filter names, lower case (empty: any file).
pub exts: Vec<String>,
/// The filter's name (`"Audio"` in `"Audio:*.mp3;*.wav"`; empty: none given).
pub label: String,
/// The filter also offers every file (`*.*`).
pub any: bool,
/// `multiSelect`: several files may be picked.
pub many: bool,
/// The file or folder the dialog starts from (`file.saveDlg`: the default name).
pub start: String,
/// A frontend has shown it (it is not shown again).
pub shown: bool,
}
/// Hands an event to the script that owns the window; returns what the handler reported
/// (`{ok, output, error}`) and updates [`Session::script_ui`].
pub type ScriptUiDispatch = fn(&mut Session, &ScriptUiEvent) -> std::result::Result<Value, String>;
@@ -491,6 +535,13 @@ pub struct ScriptUi {
/// replaced, until EffectCraft quits.
#[serde(skip)]
pub startup_hosts: Vec<u32>,
/// The file dialogs scripts wait on, until `scriptui.fileDialog` answers them.
pub file_dialogs: Vec<ScriptFileDialog>,
/// A frontend shows the scripts' file dialogs (the egui UI sets it). Without one, as in
/// headless runs, `File.openDialog` and the like return `null` at once, so a script never
/// waits on a dialog nobody shows.
#[serde(skip)]
pub answers_file_dialogs: bool,
}
impl ScriptUi {
@@ -859,10 +910,63 @@ pub(crate) fn resize(s: &mut Session, p: &Value) -> Result<Value> {
dispatch(s, ScriptUiEvent { window, widget: 0, kind: "resize".into(), value: json!([w, h]) })
}
/// `scriptui.fileDialogs`: the file dialogs scripts wait on.
pub(crate) fn file_dialogs(s: &mut Session, _: &Value) -> Result<Value> {
Ok(serde_json::to_value(&s.script_ui.file_dialogs).unwrap_or(Value::Null))
}
/// `scriptui.fileDialog`: answer a script's file dialog with the picked `paths` (`null` or
/// empty: cancelled); the script goes on with them. The dialog stays pending until its script
/// has the answer, so a refused answer leaves it to be answered again.
pub(crate) fn file_dialog(s: &mut Session, p: &Value) -> Result<Value> {
let c = "scriptui.fileDialog";
// A script answering a dialog (its own or another script's) would only be refused when the
// answer is handed over: scripts can't drive script windows.
if s.running_for_script() {
return Err(crate::commands::bad(c, "scripts can't answer file dialogs"));
}
let num = |k: &str| p.get(k).map(|v| v.as_u64().and_then(|n| u32::try_from(n).ok()));
let pending = &s.script_ui.file_dialogs;
let asked = match (num("id"), num("host")) {
(Some(id), _) => id.and_then(|id| pending.iter().find(|d| d.id == id)),
(None, Some(host)) => host.and_then(|h| pending.iter().find(|d| d.host == h)),
(None, None) if pending.len() == 1 => pending.first(),
(None, None) => None,
};
let asked = asked.cloned().ok_or_else(|| crate::commands::bad(c, "no such file dialog (give `id` from scriptui.fileDialogs)"))?;
let mut paths: Vec<String> = match p.get("paths").or_else(|| p.get("path")) {
None | Some(Value::Null) => vec![],
Some(Value::String(one)) => vec![one.clone()],
Some(Value::Array(a)) => {
a.iter().map(|v| v.as_str().map(str::to_string)).collect::<Option<Vec<_>>>().ok_or_else(|| crate::commands::bad(c, "`paths` must be strings"))?
}
Some(other) => return Err(crate::commands::bad(c, format!("`paths` must be a list of paths or null, not {other}"))),
};
paths.retain(|p| !p.is_empty());
if !asked.many {
paths.truncate(1);
}
let paths = if paths.is_empty() { Value::Null } else { json!(paths) };
// The scripting engine takes the dialog off the list when its script has the answer.
let value = json!({"id": asked.id, "host": asked.host, "paths": paths});
dispatch(s, ScriptUiEvent { window: 0, widget: 0, kind: FILE_DIALOG_EVENT.into(), value })
}
/// `scriptui.close`: close a window (a dialog's `show()` returns `result`, default 2 = Cancel).
pub(crate) fn close(s: &mut Session, p: &Value) -> Result<Value> {
let window = window_p(s, p, "scriptui.close")?;
let result = p.get("result").cloned().unwrap_or(json!(2));
// A script waiting on its file dialog (one whose answer never came) can still be closed:
// the file dialog counts as cancelled first. If that is refused, the close is tried all the
// same (and refused with its own reason).
let host = s.script_ui.window(window).map(|w| w.host);
let asked = host.and_then(|h| s.script_ui.file_dialogs.iter().find(|d| d.host == h)).map(|d| d.id);
if let Some(id) = asked
&& let Ok(cancelled) = file_dialog(s, &json!({"id": id, "paths": null}))
&& s.script_ui.window(window).is_none()
{
return Ok(cancelled);
}
dispatch(s, ScriptUiEvent { window, widget: 0, kind: "close".into(), value: result })
}
+18 -6
View File
@@ -287,11 +287,23 @@ File.prototype = {
copy: function (to) { return JSON.parse(__file("copy", this.__path, __str(to))); },
rename: function () { throw __err("File.rename is not supported"); },
execute: function () { return JSON.parse(__file("execute", this.__path)); },
openDlg: function () { return null; },
saveDlg: function () { return null; },
openDlg: function (prompt, filter, multiSelect) { return __pickFile("open", prompt, filter, multiSelect, this.__path); },
saveDlg: function (prompt, filter) { return __pickFile("save", prompt, filter, false, this.__path); },
};
File.openDialog = function () { return null; };
File.saveDialog = function () { return null; };
// The app's file dialog (#2778): a File (an array of them with multiSelect), a Folder for
// "folder", or null when cancelled, and where no dialog can be shown (the Script Console, the
// web, headless runs). Filters are strings ("*.jsx", "Audio:*.mp3;*.wav"); a function (macOS)
// offers every file.
function __pickFile(kind, prompt, filter, multiSelect, start) {
var opt = function (v) { return v === undefined || v === null ? null : __str(v); };
var r = JSON.parse(__fileDialog(kind, opt(prompt), typeof filter === "string" ? filter : null, !!multiSelect, opt(start)));
if (!r || !r.length) return null;
if (kind === "folder") return new Folder(r[0]);
if (kind === "open" && multiSelect) return r.map(function (p) { return new File(p); });
return new File(r[0]);
}
File.openDialog = function (prompt, filter, multiSelect) { return __pickFile("open", prompt, filter, multiSelect); };
File.saveDialog = function (prompt, filter) { return __pickFile("save", prompt, filter, false); };
File.decode = function (s) { return decodeURIComponent(s); };
File.encode = function (s) { return encodeURIComponent(s); };
File.fs = "EffectCraft";
@@ -354,9 +366,9 @@ Folder.prototype = {
}
return out;
},
selectDlg: function () { return null; },
selectDlg: function (prompt) { return __pickFile("folder", prompt, null, false, this.__path); },
};
Folder.selectDialog = function () { return null; };
Folder.selectDialog = function (prompt) { return __pickFile("folder", prompt, null, false); };
Object.defineProperty(Folder, "current", { get: function () { var d = __get("app").projectDir; return d ? new Folder(d) : null; } });
Object.defineProperty(Folder, "temp", { get: function () { return null; } });
Object.defineProperty(Folder, "desktop", { get: function () { return null; } });
+2 -1
View File
@@ -562,7 +562,7 @@ pub(crate) fn new_context() -> Result<Context, String> {
let limits = ctx.runtime_limits_mut();
limits.set_loop_iteration_limit(200_000_000);
limits.set_recursion_limit(2000);
let natives: [(JsString, usize, fn(&JsValue, &[JsValue], &mut Context) -> JsResult<JsValue>); 11] = [
let natives: [(JsString, usize, fn(&JsValue, &[JsValue], &mut Context) -> JsResult<JsValue>); 12] = [
(js_string!("__exec"), 2, native_exec),
(js_string!("__query"), 2, native_query),
(js_string!("__print"), 1, native_print),
@@ -574,6 +574,7 @@ pub(crate) fn new_context() -> Result<Context, String> {
(js_string!("__uiNewId"), 0, crate::ui::native_new_id),
(js_string!("__uiModal"), 1, crate::ui::native_modal),
(js_string!("__uiLayoutNative"), 1, crate::ui::native_layout),
(js_string!("__fileDialog"), 5, crate::ui::native_file_dialog),
];
for (name, len, f) in natives {
ctx.register_global_callable(name, len, NativeFunction::from_fn_ptr(f)).map_err(|e| e.to_string())?;
+15
View File
@@ -288,3 +288,18 @@ fn empty_or_missing_folders_run_nothing() {
crate::install(&mut s);
assert_eq!(s.execute("file.runShutdownScripts", json!({})).unwrap(), none);
}
/// #2778: the app is quitting, so nothing would show a Shutdown script's file dialog: it gets null
/// at once instead of waiting for good.
#[test]
fn a_shutdown_script_file_dialog_does_not_wait() {
let store = Arc::new(MemoryConfig::default());
let probe = r#"var f = File.saveDialog("Save the log", "*.txt"); app.settings.saveSetting("Startup Test", "log", f === null ? "none" : "asked");"#;
store.write(&format!("{SHUTDOWN_DIR}/Save Log.jsx"), probe).unwrap();
let mut s = session(&store);
s.script_ui.answers_file_dialogs = true;
let r = s.execute("file.runShutdownScripts", json!({})).unwrap();
assert_eq!(r, json!({"ran": ["Save Log.jsx"], "waiting": [], "failed": []}));
assert_eq!(setting(&mut s, "log"), "none");
assert!(s.script_ui.file_dialogs.is_empty());
}
+122
View File
@@ -297,3 +297,125 @@ fn sample_scripts_and_installing() {
let _ = std::fs::remove_dir_all(&dir);
let _: Value = json!(null);
}
const PICK_AUDIO: &str = r#"
var d = new Window("dialog", "Pick Audio");
var song = d.add("edittext", undefined, "", { name: "song" });
var browse = d.add("button", undefined, "Browse...", { name: "browse" });
browse.onClick = function () {
var f = File.openDialog("Select a song", "Audio:*.MP3;*.wav,All files:*.*");
song.text = f ? f.fsName : "(cancelled)";
};
var where = d.add("button", undefined, "Folder...", { name: "where" });
where.onClick = function () {
var f = Folder.selectDialog("Output folder");
song.text = f instanceof Folder ? "folder " + f.fsName : "(cancelled)";
};
d.add("button", undefined, "OK", { name: "ok" });
var r = d.show();
r + " " + song.text
"#;
/// #2778: File.openDialog, Folder.selectDialog… in a dialog's Browse… handler. With a frontend
/// that shows scripts' file dialogs, the script waits for `scriptui.fileDialog`'s answer (the
/// picked files, or null when cancelled); headless runs get null at once.
#[test]
fn file_dialogs_wait_for_their_answer() {
let mut s = session();
// Headless: nothing shows a dialog, so the script never waits on one.
let o = run_code(&mut s, r#"var f = File.openDialog("Pick"); f === null ? "none" : "picked""#, "headless.jsx");
assert!(!o.waiting && o.error.is_none(), "{o:?}");
assert_eq!(o.result, json!("none"));
assert!(s.script_ui.file_dialogs.is_empty());
s.script_ui.answers_file_dialogs = true;
// At the top of a script, with multiSelect: an array of Files.
let o = run_code(&mut s, r#"var fs = File.openDialog("Pick scripts", "*.jsx", true); fs ? fs.length + " " + fs[1].name : "none""#, "top.jsx");
assert!(o.waiting, "{o:?}");
let asked = s.execute("scriptui.fileDialogs", json!({})).unwrap();
assert_eq!(asked[0]["kind"], "open", "{asked}");
assert_eq!((asked[0]["prompt"].clone(), asked[0]["exts"].clone(), asked[0]["many"].clone()), (json!("Pick scripts"), json!(["jsx"]), json!(true)));
let r = s.execute("scriptui.fileDialog", json!({"paths": ["/a/x.jsx", "/b/y.jsx"]})).unwrap();
assert_eq!(r["result"], "2 y.jsx", "{r}");
assert!(s.script_ui.file_dialogs.is_empty());
// In a modal dialog's Browse… handler.
let o = run_code(&mut s, PICK_AUDIO, "pick.jsx");
assert!(o.waiting, "{o:?}");
let r = s.execute("scriptui.click", json!({"widget": "browse"})).unwrap();
assert_eq!(r["waiting"], true, "{r}");
let asked = s.script_ui.file_dialogs.clone();
assert_eq!(asked.len(), 1);
assert_eq!(asked[0].exts, ["mp3", "wav"], "the filter's extensions, `*.*` adds none");
assert_eq!((asked[0].label.as_str(), asked[0].any, asked[0].many), ("Audio", true, false));
// An answer for another dialog (a stale one) is refused; this one still waits.
let e = s.execute("scriptui.fileDialog", json!({"id": asked[0].id + 1000, "paths": null})).unwrap_err().to_string();
assert!(e.contains("no such file dialog"), "{e}");
assert_eq!(s.script_ui.file_dialogs.len(), 1);
// The dialog's controls wait for the answer.
let e = s.execute("scriptui.click", json!({"widget": "ok"})).unwrap_err().to_string();
assert!(e.contains("waiting for its file dialog"), "{e}");
// Cancelled: null.
s.execute("scriptui.fileDialog", json!({"paths": null})).unwrap();
let song = |s: &Session| s.script_ui.windows[0].root.lookup(&json!("song")).map(|w| w.text.clone()).unwrap_or_default();
assert_eq!(song(&s), "(cancelled)");
s.execute("scriptui.click", json!({"widget": "browse"})).unwrap();
// Only one file without multiSelect.
s.execute("scriptui.fileDialog", json!({"paths": ["/media/song.wav", "/media/other.wav"]})).unwrap();
assert_eq!(song(&s), "/media/song.wav");
s.execute("scriptui.click", json!({"widget": "where"})).unwrap();
assert_eq!(s.script_ui.file_dialogs[0].kind, effectcraft_engine::scriptui::FileDialogKind::Folder);
s.execute("scriptui.fileDialog", json!({"paths": ["/media/out"]})).unwrap();
assert_eq!(song(&s), "folder /media/out");
let r = s.execute("scriptui.click", json!({"widget": "ok"})).unwrap();
assert_eq!(r["result"], "1 folder /media/out", "{r}");
// Nothing waits any more.
assert!(s.execute("scriptui.fileDialog", json!({"paths": null})).is_err());
// A file dialog whose answer never comes doesn't trap its script window: closing it cancels
// the file dialog, then closes the window.
let o = run_code(&mut s, PICK_AUDIO, "pick.jsx");
assert!(o.waiting, "{o:?}");
s.execute("scriptui.click", json!({"widget": "browse"})).unwrap();
assert_eq!(s.script_ui.file_dialogs.len(), 1);
let r = s.execute("scriptui.close", json!({})).unwrap();
assert_eq!(r["result"], "2 (cancelled)", "{r}");
assert!(s.script_ui.windows.is_empty() && s.script_ui.file_dialogs.is_empty());
}
/// A script can't answer or close another script's waiting file dialog (it would take the dialog
/// off the list and leave its script waiting for good): refused, and the window still closes.
#[test]
fn scripts_cannot_strand_a_waiting_file_dialog() {
let mut s = session();
s.script_ui.answers_file_dialogs = true;
let o = run_code(&mut s, PICK_AUDIO, "pick.jsx");
assert!(o.waiting, "{o:?}");
s.execute("scriptui.click", json!({"widget": "browse"})).unwrap();
let (window, id) = (s.script_ui.windows[0].id, s.script_ui.file_dialogs[0].id);
// From the Script Console.
for (command, params) in [("scriptui.close", json!({"window": window})), ("scriptui.fileDialog", json!({"id": id, "paths": ["/x.wav"]}))] {
let code = format!("try {{ __exec({command:?}, {:?}); \"ran\" }} catch (e) {{ \"refused\" }}", params.to_string());
let o = crate::run(&mut s, &effectcraft_engine::ScriptRequest { code: &code, name: "console", console: true });
assert_eq!(o.result, json!("refused"), "{command}: {o:?}");
assert_eq!(s.script_ui.file_dialogs.len(), 1, "{command}: the dialog still waits");
}
let r = s.execute("scriptui.close", json!({"window": window})).unwrap();
assert_eq!(r["result"], "2 (cancelled)", "{r}");
assert!(s.script_ui.windows.is_empty() && s.script_ui.file_dialogs.is_empty());
}
#[test]
fn file_dialog_filters_name_their_extensions() {
use crate::ui::filter_exts;
assert_eq!(filter_exts("*.jsx"), ["jsx"]);
assert_eq!(filter_exts("Audio:*.MP3;*.wav,All files:*.*"), ["mp3", "wav"]);
assert_eq!(filter_exts("Images (*.png, *.jpg)|*.png;*.jpg"), ["png", "jpg"]);
assert!(filter_exts("*.*").is_empty() && filter_exts("").is_empty() && filter_exts("*.").is_empty());
use crate::ui::{filter_any, filter_label};
assert_eq!(filter_label("Audio:*.mp3;*.wav,All files:*.*"), "Audio");
assert_eq!(filter_label("Images (*.png, *.jpg)|*.png;*.jpg"), "Images");
assert_eq!(filter_label("*.jsx"), "");
assert!(filter_any("Audio:*.mp3,All files:*.*") && filter_any("Any|*"));
assert!(!filter_any("*.jsx") && !filter_any(""));
}
+150 -18
View File
@@ -18,7 +18,7 @@ use std::sync::atomic::{AtomicU32, Ordering};
use boa_engine::{Context, JsResult, JsValue, js_string};
use effectcraft_engine::Session;
use effectcraft_engine::scriptui::{ScriptUiEvent, ScriptWindow, layout};
use effectcraft_engine::scriptui::{FILE_DIALOG_EVENT, FileDialogKind, ScriptFileDialog, ScriptUiEvent, ScriptWindow, layout};
use serde_json::{Value as J, json};
use web_time::Instant;
@@ -126,6 +126,116 @@ pub(crate) fn native_modal(_: &JsValue, args: &[JsValue], ctx: &mut Context) ->
}
}
/// The extensions a ScriptUI file filter names, lower case: `"*.wav"`, `"Audio:*.mp3;*.wav,All
/// files:*.*"` (Windows), `"Audio (*.mp3, *.wav)|*.mp3;*.wav"`… Wildcard-only patterns (`*.*`)
/// name none; a filter without extensions (or a macOS filter function) offers every file.
pub(crate) fn filter_exts(filter: &str) -> Vec<String> {
const MAX_EXTS: usize = 64;
const MAX_LEN: usize = 16;
let mut out: Vec<String> = vec![];
for part in filter.split("*.").skip(1) {
let ext: String = part.chars().take_while(char::is_ascii_alphanumeric).collect();
if ext.is_empty() || ext.len() > MAX_LEN {
continue;
}
let ext = ext.to_ascii_lowercase();
if !out.contains(&ext) {
out.push(ext);
}
if out.len() >= MAX_EXTS {
break;
}
}
out
}
/// The name a ScriptUI file filter gives its first entry (`"Audio"` in `"Audio:*.mp3;*.wav"`,
/// `"Audio (*.mp3)|*.mp3"`); empty when it gives none.
pub(crate) fn filter_label(filter: &str) -> String {
const MAX_LEN: usize = 64;
let Some(end) = filter.find([':', '|']) else { return String::new() };
// "Audio (*.mp3, *.wav)": the name without its list of patterns.
let label = filter.get(..end).unwrap_or_default();
let label = label.split('(').next().unwrap_or_default().trim();
if label.contains('*') { String::new() } else { label.chars().take(MAX_LEN).collect() }
}
/// Whether a ScriptUI file filter also offers every file (`*.*`, or a bare `*` pattern).
pub(crate) fn filter_any(filter: &str) -> bool {
filter.contains("*.*") || filter.split([':', '|', ';', ',']).any(|p| p.trim() == "*")
}
static NEXT_FILE_DIALOG: AtomicU32 = AtomicU32::new(1);
/// Argument `i` as text; empty when null or missing.
fn text_arg(args: &[JsValue], i: usize, ctx: &mut Context) -> JsResult<String> {
match args.get(i) {
None => Ok(String::new()),
Some(v) if v.is_null() || v.is_undefined() => Ok(String::new()),
Some(v) => Ok(v.to_string(ctx)?.to_std_string_escaped()),
}
}
/// `__fileDialog(kind, prompt, filter, multiSelect, start)` → `[path…]` JSON or `null`:
/// `File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the instance `openDlg` /
/// `saveDlg` / `selectDlg` (#2778). On a script-host thread, with a frontend that shows the
/// scripts' file dialogs ([`effectcraft_engine::scriptui::ScriptUi::answers_file_dialogs`]), it
/// asks for the dialog ([`ScriptFileDialog`]), hands the session back to the caller like a modal
/// dialog does and waits for `scriptui.fileDialog`'s answer. Elsewhere (the Script Console, the
/// web, headless runs) there is no dialog to wait on: `null`, as a cancelled dialog.
pub(crate) fn native_file_dialog(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let kind = match arg_string(args, 0, ctx)?.as_str() {
"save" => FileDialogKind::Save,
"folder" => FileDialogKind::Folder,
_ => FileDialogKind::Open,
};
let prompt = text_arg(args, 1, ctx)?;
let filter = text_arg(args, 2, ctx)?;
let start = text_arg(args, 4, ctx)?;
let many = kind == FileDialogKind::Open && args.get(3).is_some_and(JsValue::to_boolean);
let id = NEXT_FILE_DIALOG.fetch_add(1, Ordering::Relaxed);
let asked = with_active(|a| {
if a.link.is_none() || !a.session.script_ui.answers_file_dialogs {
return Ok(false);
}
// One dialog at a time per script.
a.session.script_ui.file_dialogs.retain(|d| d.host != a.host);
let folder = kind == FileDialogKind::Folder;
let (exts, label, any) = if folder { (vec![], String::new(), false) } else { (filter_exts(&filter), filter_label(&filter), filter_any(&filter)) };
a.session.script_ui.file_dialogs.push(ScriptFileDialog { id, host: a.host, kind, prompt, exts, label, any, many, start, shown: false });
Ok(true)
})
.unwrap_or(false);
if !asked {
return Ok(JsValue::null());
}
let forget = || {
let _ = with_active(|a| {
a.session.script_ui.file_dialogs.retain(|d| d.id != id);
Ok(())
});
};
loop {
let windows = snapshot(ctx);
let out = crate::Outcome { output: settle(), waiting: true, ..Default::default() };
// The caller went away: as cancelled.
let Some(ev) = yield_wait(out, windows, false) else { return Ok(JsValue::null()) };
if ev.kind == FILE_DIALOG_EVENT {
// An answer to an earlier dialog of this script is not this one's.
if ev.value.get("id").and_then(J::as_u64) == Some(u64::from(id)) {
forget();
let paths = ev.value.get("paths").cloned().unwrap_or(J::Null);
return Ok(js_str(&paths.to_string()));
}
} else if ev.kind == "close" {
// `dispatch_ui` refuses the script's window events while it waits; a close that got
// here all the same ends the wait as cancelled, so the window can be closed.
forget();
return Ok(JsValue::null());
}
}
}
// ---------------------------------------------------------------- script-host threads
pub(crate) enum ToHost {
@@ -320,8 +430,7 @@ fn receive(session: &mut Session, host: u32, end: HostEnd) -> crate::Outcome {
}
publish(session, host, &name, windows);
if done {
session.script_ui.windows.retain(|w| w.host != host);
session.script_ui.revision += 1;
forget_host(session, host);
} else if let Ok(mut h) = hosts().lock() {
h.insert(host, HostEnd { next_due, epoch: session.script_ui.project_epoch, ..end });
}
@@ -331,6 +440,13 @@ fn receive(session: &mut Session, host: u32, end: HostEnd) -> crate::Outcome {
}
}
/// A script host has ended: its windows close and nothing waits on its file dialogs.
fn forget_host(session: &mut Session, host: u32) {
session.script_ui.windows.retain(|w| w.host != host);
session.script_ui.file_dialogs.retain(|d| d.host != host);
session.script_ui.revision += 1;
}
/// Run a script file on a new script-host thread (see the module docs). Not on the web, where
/// scripts run inline.
#[cfg(not(target_arch = "wasm32"))]
@@ -434,22 +550,33 @@ pub fn dispatch_ui(session: &mut Session, ev: &ScriptUiEvent) -> Result<J, Strin
if ACTIVE.with(|a| a.try_borrow().map(|g| g.is_some()).unwrap_or(true)) {
return Err("scripts can't drive script windows".into());
}
let w = session.script_ui.window(ev.window).ok_or_else(|| format!("no script window {}", ev.window))?;
let (host, name) = (w.host, w.script.clone());
let inline = host == CONSOLE_HOST || INLINE.with(|m| m.borrow().contains_key(&host));
if inline {
return Ok(dispatch_inline(session, host, &name, ev).to_json());
}
let host = if ev.kind == FILE_DIALOG_EVENT {
// The answer to a file dialog goes to the script waiting on it (only script-host
// threads wait on one, see [`native_file_dialog`]).
let id = ev.value.get("id").and_then(J::as_u64);
let asked = session.script_ui.file_dialogs.iter().find(|d| Some(u64::from(d.id)) == id);
asked.map(|d| d.host).ok_or("no such file dialog")?
} else {
let w = session.script_ui.window(ev.window).ok_or_else(|| format!("no script window {}", ev.window))?;
let (host, name) = (w.host, w.script.clone());
// The script is inside its file dialog's call: its windows wait for the answer.
if session.script_ui.file_dialogs.iter().any(|d| d.host == host) {
return Err("the script is waiting for its file dialog".into());
}
let inline = host == CONSOLE_HOST || INLINE.with(|m| m.borrow().contains_key(&host));
if inline {
return Ok(dispatch_inline(session, host, &name, ev).to_json());
}
host
};
let end = hosts().lock().ok().and_then(|mut h| h.remove(&host));
let Some(end) = end else {
session.script_ui.windows.retain(|w| w.host != host);
session.script_ui.revision += 1;
forget_host(session, host);
return Err("the script that made this window has ended".into());
};
if let Err(std::sync::mpsc::SendError(msg)) = end.tx.send(ToHost::Event(std::mem::take(session), ev.clone())) {
*session = msg.into_session();
session.script_ui.windows.retain(|w| w.host != host);
session.script_ui.revision += 1;
forget_host(session, host);
return Err("the script that made this window has ended".into());
}
Ok(receive(session, host, end).to_json())
@@ -487,7 +614,10 @@ fn dispatch_inline(session: &mut Session, host: u32, name: &str, ev: &ScriptUiEv
/// Whether `host`'s tasks stop now that the project it ran with was closed: it has no window
/// open and is not a Startup script's.
fn ends_with_project(session: &Session, host: u32) -> bool {
!session.script_ui.windows.iter().any(|w| w.host == host) && !session.script_ui.startup_hosts.contains(&host)
// A script waiting on its file dialog goes on when it is answered.
!session.script_ui.windows.iter().any(|w| w.host == host)
&& !session.script_ui.startup_hosts.contains(&host)
&& !session.script_ui.file_dialogs.iter().any(|d| d.host == host)
}
/// Run the due tasks of the script-host threads; hosts without windows whose project was closed
@@ -501,13 +631,16 @@ pub(crate) fn tick_threaded(session: &mut Session, now: Instant, report: &mut cr
let Some(end) = h.get(&host) else { continue };
if end.epoch != epoch && ends_with_project(session, host) {
// Dropping its end lets the host thread finish.
stale.extend(h.remove(&host));
stale.extend(h.remove(&host).map(|end| (host, end)));
} else if end.next_due.is_some_and(|d| d <= now) {
due.push(host);
}
}
}
drop(stale);
for end in stale {
forget_host(session, end.0);
drop(end.1);
}
for host in due {
if session.script_ui.render_host.is_some() {
break;
@@ -515,8 +648,7 @@ pub(crate) fn tick_threaded(session: &mut Session, now: Instant, report: &mut cr
let Some(end) = hosts().lock().ok().and_then(|mut h| h.remove(&host)) else { continue };
if let Err(std::sync::mpsc::SendError(msg)) = end.tx.send(ToHost::Tick(std::mem::take(session), now)) {
*session = msg.into_session();
session.script_ui.windows.retain(|w| w.host != host);
session.script_ui.revision += 1;
forget_host(session, host);
continue;
}
report.add(receive(session, host, end));
+3 -1
View File
@@ -31,7 +31,9 @@ impl EffectcraftApp {
/// Loads and applies the workspaces saved in the session's config directory (a failed load is reported in
/// `ui.status`), initializes the default UI, playback and render state, and registers the frontend's commands as
/// shortcutable `UiCommand`s on the session.
pub fn new(session: Session) -> Self {
pub fn new(mut session: Session) -> Self {
// Scripts' file dialogs (File.openDialog…) show here ([`panels::scriptui_view::serve_file_dialogs`]).
session.script_ui.answers_file_dialogs = true;
let mut ui = UiState::default();
let workspace_store = workspace_state::WorkspaceStore::load(session.config.as_deref(), &mut ui);
EffectcraftApp {
+12
View File
@@ -326,12 +326,21 @@ impl EffectcraftApp {
|| !self.synthetic.is_empty()
|| !self.input_waiters.is_empty()
|| self.pending_screenshots.iter().any(|s| s.slot.is_none())
|| self.script_file_dialog_waits()
|| (self.playback.playing && child_viewports);
if paint {
self.request_hidden_paint(ctx);
}
}
/// A script waits for a file dialog nobody has shown yet: dialogs are served in a UI pass
/// (`serve_file_dialogs`), so a minimized window must paint for it (#3253 review). Not while
/// a non-blocking dialog is up: the next one waits for it.
fn script_file_dialog_waits(&self) -> bool {
let one_at_a_time = self.hooks.file_dialog_async.is_some() && self.file_dialogs.any();
!one_at_a_time && self.session.script_ui.file_dialogs.iter().any(|d| !d.shown)
}
/// Ask the host for a UI pass even when the window is minimized or occluded.
///
/// Native eframe honours `RequestPaintWhileHidden`; the shared web backend does not carry it
@@ -529,6 +538,9 @@ impl EffectcraftApp {
updates_ui::show(self, &ctx);
panels::scriptui_view::sync_panels(self);
panels::scriptui_view::show_windows(self, &ctx);
// After the windows' events and the menus' commands: a script that asked for a file
// dialog in this pass gets it now.
panels::scriptui_view::serve_file_dialogs(self);
panels::learn::coach(self, &ctx);
let lift = panels::media_panels::import_card(self, ui, full);
self.draw_toast(ui, full, lift);
+10
View File
@@ -144,6 +144,16 @@ impl EffectcraftApp {
pub(crate) fn run_dialog_answers(&mut self) {
while let Ok(answer) = self.dialog_answers.1.try_recv() {
self.file_dialogs.answered();
// A script's file dialog: answered even when cancelled (the script waits on it).
if answer.command == panels::scriptui_view::FILE_DIALOG_COMMAND {
// A dialog that couldn't open says why in the status line and counts as cancelled.
let paths = answer.paths.unwrap_or_else(|e| {
self.ui.status = e;
Vec::new()
});
panels::scriptui_view::answer_file_dialog(self, &answer.params, paths);
continue;
}
menus::dialog_answered(self, answer);
}
}
+17
View File
@@ -13,6 +13,19 @@ pub enum FileDialog {
OpenProject,
/// A folder.
Folder,
/// A file (several when `many`) a script asks for (`File.openDialog`, #2778): the script's
/// filter named `label` with these extensions (none: every file), and `any`: every file
/// besides (the filter's `*.*`).
/// `prompt` is the dialog's title (empty: the system's) and `start` the file or folder it
/// opens at (empty: the system's).
Script { label: String, exts: Vec<String>, any: bool, many: bool, prompt: String, start: String },
/// A folder a script asks for (`Folder.selectDialog`, `folder.selectDlg`) with its `prompt`
/// (the dialog's title) and the folder it starts in (`start`); both empty when not given.
ScriptFolder { prompt: String, start: String },
/// Where a script wants to save (`File.saveDialog`, `file.saveDlg`): `default` (a file name
/// or path) with the script's filter (`label`, `exts`, `any` as in [`FileDialog::Script`]; no
/// extensions: the default's extension) and the script's `prompt` as the title.
ScriptSave { default: String, prompt: String, label: String, exts: Vec<String>, any: bool },
/// Where to save `default` (a file name or path) with extension `ext` (empty: no filter);
/// `project`: the project save dialog, given the file name.
Save { default: String, ext: String, project: bool },
@@ -62,6 +75,10 @@ pub struct Hooks {
/// a drag over the window (#511), and on Linux a blocking desktop-portal dialog never pumps
/// events, so the compositor marks the window as not responding (#1275).
pub file_dialog_async: Option<Box<dyn Fn(FileDialog, DialogDone)>>,
/// Shows a [`FileDialog`] and blocks until it closes: the picked paths (empty: cancelled).
/// Scripts' file dialogs use it where [`Hooks::file_dialog_async`] isn't set (Windows); without
/// it they fall back to the pickers above.
pub pick_file_dialog: Option<Box<dyn Fn(FileDialog) -> Vec<String>>>,
/// Tells the user the graphics device was lost and the window is closing, once. `saved` is
/// the auto-save of unsaved changes (`None`: nothing was unsaved), its path or why it failed.
pub device_lost: Option<Box<dyn Fn(Option<Result<String, String>>)>>,
+5
View File
@@ -538,6 +538,11 @@ impl FileDialogsUp {
self.count = self.count.saturating_add(1);
}
/// Whether one is up.
pub(crate) fn any(&self) -> bool {
self.count > 0
}
pub(crate) fn answered(&mut self) {
self.count = self.count.saturating_sub(1);
}
+33
View File
@@ -356,6 +356,39 @@ fn image(width: usize, height: usize) -> Arc<egui::ColorImage> {
Arc::new(egui::ColorImage::new([width, height], vec![egui::Color32::from_rgb(10, 20, 30); width.checked_mul(height).unwrap()]))
}
/// #3253 review: a script waits on a file dialog while the window is hidden. File dialogs are
/// served in a UI pass, so the app asks for one until the dialog is shown; a hidden window with
/// nothing waiting stays quiet.
#[test]
fn a_script_file_dialog_asks_for_a_pass_while_the_window_is_hidden() {
use effectcraft_engine::scriptui::{FileDialogKind, ScriptFileDialog};
let ctx = egui::Context::default();
let frame = eframe::Frame::_new_kittest();
let mut app = app_with_comp();
ready(&mut app, &ctx, &frame);
let asks =
|out: &egui::LogicOutput| out.viewport_commands.values().flatten().filter(|c| matches!(c, egui::ViewportCommand::RequestPaintWhileHidden)).count();
let size = egui::vec2(800.0, 480.0);
assert_eq!(asks(&tick_with(&mut app, &ctx, &frame, &raw(size))), 0, "nothing waits: a hidden window stays quiet");
app.session.script_ui.file_dialogs.push(ScriptFileDialog {
id: 1,
host: 1,
kind: FileDialogKind::Open,
prompt: String::new(),
exts: vec![],
label: String::new(),
any: true,
many: false,
start: String::new(),
shown: false,
});
assert_eq!(asks(&tick_with(&mut app, &ctx, &frame, &raw(size))), 1, "a script waits for its dialog: the hidden window paints");
if let Some(d) = app.session.script_ui.file_dialogs.first_mut() {
d.shown = true;
}
assert_eq!(asks(&tick_with(&mut app, &ctx, &frame, &raw(size))), 0, "the dialog is shown: no more passes asked for");
}
#[test]
fn a_screenshot_is_issued_only_after_settled_passes_and_writes_from_the_tick() {
let ctx = egui::Context::default();
+109
View File
@@ -540,6 +540,115 @@ fn perform(app: &mut EffectcraftApp, ctx: &egui::Context, acts: Vec<Act>) {
}
}
/// The command that answers a script's file dialog.
pub(crate) const FILE_DIALOG_COMMAND: &str = "scriptui.fileDialog";
/// The answer to a script's file dialog shown without blocking. Dropped unanswered (a dialog that
/// ended without its completion handler, a dialog thread that didn't start) it answers
/// "cancelled", so the script never waits for an answer that can't come.
struct PendingAnswer {
tx: std::sync::mpsc::Sender<crate::DialogAnswer>,
answer: Option<crate::DialogAnswer>,
}
impl PendingAnswer {
fn send(mut self, paths: Result<Vec<String>, String>) {
if let Some(a) = self.answer.take() {
let _ = self.tx.send(crate::DialogAnswer { paths, ..a });
}
}
}
impl Drop for PendingAnswer {
fn drop(&mut self) {
if let Some(a) = self.answer.take() {
let _ = self.tx.send(a);
}
}
}
/// Show the file dialog a script waits on (`File.openDialog`, `File.saveDialog`,
/// `Folder.selectDialog`… from a ScriptUI Browse… button, #2778) and hand the answer back
/// through `scriptui.fileDialog`. Where blocking the frame is unsafe the dialog shows without
/// blocking ([`crate::Hooks::file_dialog_async`]), one at a time, and answers when it closes; a
/// host without a dialog answers "cancelled" at once, so the script never waits for nothing.
pub fn serve_file_dialogs(app: &mut EffectcraftApp) {
use effectcraft_engine::scriptui::FileDialogKind;
let spawn = app.hooks.file_dialog_async.is_some();
// A non-blocking dialog already up: the next one shows after it.
if spawn && app.file_dialogs.any() {
return;
}
let Some(asked) = app.session.script_ui.file_dialogs.iter_mut().find(|d| !d.shown) else { return };
asked.shown = true;
let asked = asked.clone();
let params = json!({"id": asked.id});
// The save dialog's default: the script's file, else a name with the filter's extension.
let default = match (asked.start.is_empty(), asked.exts.first()) {
(false, _) => asked.start.clone(),
(true, Some(ext)) => format!("Untitled.{ext}"),
(true, None) => "Untitled".to_string(),
};
let request = match asked.kind {
FileDialogKind::Open => crate::FileDialog::Script {
label: asked.label.clone(),
exts: asked.exts.clone(),
any: asked.any,
many: asked.many,
prompt: asked.prompt.clone(),
start: asked.start.clone(),
},
FileDialogKind::Save => crate::FileDialog::ScriptSave {
default: default.clone(),
prompt: asked.prompt.clone(),
label: asked.label.clone(),
exts: asked.exts.clone(),
any: asked.any,
},
FileDialogKind::Folder => crate::FileDialog::ScriptFolder { prompt: asked.prompt.clone(), start: asked.start.clone() },
};
if let Some(spawn) = app.hooks.file_dialog_async.as_ref() {
let answer = crate::DialogAnswer { command: FILE_DIALOG_COMMAND.to_string(), key: "paths", params, paths: Ok(Vec::new()) };
let pending = PendingAnswer { tx: app.dialog_answers.0.clone(), answer: Some(answer) };
app.file_dialogs.opened();
spawn(request, Box::new(move |paths| pending.send(paths)));
return;
}
let paths: Vec<String> = match (&app.hooks.pick_file_dialog, asked.kind) {
(Some(pick), _) => pick(request),
(_, FileDialogKind::Open) => {
let exts: Vec<&str> = asked.exts.iter().map(String::as_str).collect();
app.hooks.pick_files.as_ref().map(|pick| pick(&exts)).unwrap_or_default()
}
(_, FileDialogKind::Save) => app.hooks.save_dialog(&default).flatten().into_iter().collect(),
(_, FileDialogKind::Folder) => app.hooks.pick_folder.as_ref().and_then(|pick| pick()).into_iter().collect(),
};
let paths = if asked.many { paths } else { paths.into_iter().take(1).collect() };
answer_file_dialog(app, &params, paths);
}
/// Answer a script's file dialog (`params`: `{id}`) with the picked `paths` (empty: cancelled);
/// what the script then reports shows as [`perform`] shows a handler's. An answer that comes
/// after the dialog was dropped (its script window closed meanwhile) is let go.
pub(crate) fn answer_file_dialog(app: &mut EffectcraftApp, params: &Value, paths: Vec<String>) {
let id = params.get("id").and_then(Value::as_u64);
if !app.session.script_ui.file_dialogs.iter().any(|d| Some(u64::from(d.id)) == id) {
return;
}
let paths = if paths.is_empty() { Value::Null } else { json!(paths) };
match app.session.execute(FILE_DIALOG_COMMAND, json!({"id": id, "paths": paths})) {
Ok(r) => {
if let Some(e) = r.get("error").filter(|e| !e.is_null()) {
let msg = e["message"].as_str().unwrap_or("script error").to_string();
app.toast = Some((msg, app.now()));
} else if let Some(o) = r["output"].as_str().filter(|o| !o.is_empty()) {
app.ui.status = o.lines().last().unwrap_or_default().to_string();
}
}
Err(e) => app.ui.status = e.to_string(),
}
}
/// The floating script windows (dialogs, palettes, windows), drawn over the app.
pub fn show_windows(app: &mut EffectcraftApp, ctx: &egui::Context) {
let windows: Vec<ScriptWindow> = app.session.script_ui.windows.iter().filter(|w| w.kind != WindowKind::Panel).cloned().collect();
+162
View File
@@ -398,3 +398,165 @@ fn scheduled_import_reveals_its_composition_without_manual_clicks() {
assert!(!h.state().ui.start_screen, "Home must not hide a composition opened by the scheduled import");
h.state_mut().session.execute("scriptui.close", json!({"window":"Automatic import"})).unwrap();
}
/// #2778: a script dialog's Browse… button calls `File.openDialog` / `Folder.selectDialog`; the
/// app shows its file dialog (with the script's filter) and the script goes on with the picked
/// file, or with null when cancelled. Blocking dialogs (Windows) answer in the same pass; the
/// non-blocking ones (macOS, Linux) when they close.
#[test]
fn script_browse_buttons_open_the_file_dialog() {
use std::sync::{Arc, Mutex};
let mut h = harness();
let picked = std::env::temp_dir().join("Song.wav").to_string_lossy().to_string();
let asked: Arc<Mutex<Vec<Vec<String>>>> = Arc::default();
let (log, file) = (asked.clone(), picked.clone());
h.state_mut().hooks.pick_files = Some(Box::new(move |exts: &[&str]| {
log.lock().unwrap().push(exts.iter().map(|e| e.to_string()).collect());
vec![file.clone()]
}));
// Cancelled.
h.state_mut().hooks.pick_folder = Some(Box::new(|| None::<String>));
let code = r#"
var d = new Window("dialog", "Pick Audio");
var row = d.add("group");
var song = row.add("edittext", undefined, "", { name: "song" });
song.characters = 30;
var browse = row.add("button", undefined, "Browse...", { name: "browse" });
browse.onClick = function () {
var f = File.openDialog("Select a song", "Audio:*.mp3;*.wav,All files:*.*");
song.text = f ? f.fsName : "(cancelled)";
};
var out = d.add("edittext", undefined, "", { name: "out" });
var where = d.add("button", undefined, "Folder...", { name: "where" });
where.onClick = function () {
var f = Folder.selectDialog("Output folder");
out.text = f ? f.fsName : "(cancelled)";
};
d.add("button", undefined, "OK", { name: "ok" });
if (d.show() === 1) app.project.activeItem.layers.addNull().name = song.text + " | " + out.text;
"#;
let r = h.state_mut().session.execute("script.run", json!({"code": code, "name": "pick.jsx"})).unwrap();
assert_eq!(r["waiting"], true, "{r}");
h.run_steps(3);
let d = h.state().session.script_ui.windows.iter().find(|w| w.modal).unwrap().id;
let text = |h: &Harness<'_, EffectcraftApp>, name: &str| {
h.state().session.script_ui.window(d).and_then(|w| w.root.lookup(&json!(name))).map(|w| w.text.clone()).unwrap_or_default()
};
click(&mut h, &format!("scriptui.{d}.browse"));
assert_eq!(*asked.lock().unwrap(), [vec!["mp3".to_string(), "wav".to_string()]], "Browse… opens the file dialog with the script's filter");
assert_eq!(text(&h, "song"), picked, "the script gets the picked file");
click(&mut h, &format!("scriptui.{d}.where"));
assert_eq!(text(&h, "out"), "(cancelled)", "a cancelled dialog gives the script null");
// A dialog that doesn't block the frame answers when it closes.
let done: Arc<Mutex<Vec<(effectcraft_ui_egui::FileDialog, effectcraft_ui_egui::DialogDone)>>> = Arc::default();
let queue = done.clone();
h.state_mut().hooks.file_dialog_async = Some(Box::new(move |dialog, answer| queue.lock().unwrap().push((dialog, answer))));
click(&mut h, &format!("scriptui.{d}.where"));
let (dialog, answer) = done.lock().unwrap().pop().expect("the folder dialog is asked for");
assert_eq!(dialog, effectcraft_ui_egui::FileDialog::ScriptFolder { prompt: "Output folder".into(), start: String::new() });
let folder = std::env::temp_dir().to_string_lossy().to_string();
answer(Ok(vec![folder.clone()]));
h.run_steps(3);
assert_eq!(text(&h, "out"), folder);
// A dialog that ends without answering (its completion handler never runs) counts as
// cancelled: the script doesn't wait for good.
h.state_mut().hooks.file_dialog_async = Some(Box::new(|_: effectcraft_ui_egui::FileDialog, answer: effectcraft_ui_egui::DialogDone| drop(answer)));
click(&mut h, &format!("scriptui.{d}.where"));
h.run_steps(3);
assert_eq!(text(&h, "out"), "(cancelled)");
// The dialog still works: OK closes it and the script runs on.
click(&mut h, &format!("scriptui.{d}.ok"));
assert_eq!(layer_names(&h), [format!("{picked} | (cancelled)")]);
assert!(h.state().session.script_ui.windows.is_empty());
}
/// #2778 review: the prompt, the start location and the full filter of a script's instance
/// `openDlg` / `saveDlg` / `selectDlg` reach the host's dialog, not just the filter's extensions.
#[test]
fn script_file_dialog_options_reach_the_host_dialog() {
use effectcraft_ui_egui::FileDialog;
use std::sync::{Arc, Mutex};
let mut h = harness();
let asked: Arc<Mutex<Vec<FileDialog>>> = Arc::default();
let log = asked.clone();
h.state_mut().hooks.pick_file_dialog = Some(Box::new(move |dialog| {
log.lock().unwrap().push(dialog);
Vec::new()
}));
let dir = std::env::temp_dir().to_string_lossy().to_string();
let code = format!(
r#"
var d = new Window("dialog", "Options");
d.add("button", undefined, "Open", {{ name: "open" }}).onClick = function () {{ new File({dir:?}).openDlg("Pick a song", "Audio:*.mp3;*.wav,All files:*.*", false); }};
d.add("button", undefined, "Save", {{ name: "save" }}).onClick = function () {{ new File({dir:?} + "/Mix.wav").saveDlg("Save the mix", "Audio:*.wav;*.aif"); }};
d.add("button", undefined, "Folder", {{ name: "folder" }}).onClick = function () {{ new Folder({dir:?}).selectDlg("Output folder"); }};
d.add("button", undefined, "OK", {{ name: "ok" }});
d.show();
"#
);
let r = h.state_mut().session.execute("script.run", json!({"code": code, "name": "opts.jsx"})).unwrap();
assert_eq!(r["waiting"], true, "{r}");
h.run_steps(3);
let d = h.state().session.script_ui.windows.iter().find(|w| w.modal).unwrap().id;
for name in ["open", "save", "folder"] {
click(&mut h, &format!("scriptui.{d}.{name}"));
}
let got = asked.lock().unwrap().clone();
let exts = |e: &[&str]| e.iter().map(|e| e.to_string()).collect::<Vec<_>>();
assert_eq!(
got,
[
FileDialog::Script { label: "Audio".into(), exts: exts(&["mp3", "wav"]), any: true, many: false, prompt: "Pick a song".into(), start: dir.clone() },
FileDialog::ScriptSave {
default: format!("{dir}/Mix.wav"),
prompt: "Save the mix".into(),
label: "Audio".into(),
exts: exts(&["wav", "aif"]),
any: false
},
FileDialog::ScriptFolder { prompt: "Output folder".into(), start: dir.clone() },
],
"the dialogs carry the script's prompt, start location and whole filter"
);
}
/// #2894: the same from a dockable ScriptUI panel (Window ▸ <panel>): its button's
/// `File.openDialog` opens the file dialog and the panel's handler goes on with the file.
#[test]
fn a_docked_panel_button_opens_the_file_dialog() {
use effectcraft_engine::config::{ConfigStore, MemoryConfig};
use std::sync::{Arc, Mutex};
let store = Arc::new(MemoryConfig::default());
let panel = r#"
var p = this;
var status = p.add("statictext", undefined, "No file selected", { name: "status" });
status.characters = 40;
var pick = p.add("button", undefined, "Select SRT File", { name: "pick" });
pick.onClick = function () {
var f = File.openDialog("Select an SRT file", "Subtitles:*.srt;All Files:*.*");
status.text = f ? f.name : "No file selected";
};
p.layout.layout(true);
"#;
store.write("Scripts/ScriptUI Panels/Subtitles Panel.jsx", panel).unwrap();
let mut s = effectcraft_host::session();
s.config = Some(store.clone());
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_| EffectcraftApp::new(s));
h.run_steps(3);
let asked: Arc<Mutex<Vec<Vec<String>>>> = Arc::default();
let log = asked.clone();
let file = std::env::temp_dir().join("Episode 1.srt").to_string_lossy().to_string();
h.state_mut().hooks.pick_files = Some(Box::new(move |exts: &[&str]| {
log.lock().unwrap().push(exts.iter().map(|e| e.to_string()).collect());
vec![file.clone()]
}));
h.state_mut().session.execute("window.scriptPanel", json!({"name": "Subtitles Panel.jsx"})).unwrap();
h.run_steps(3);
let panel = h.state().session.script_ui.windows.iter().find(|w| w.script == "Subtitles Panel.jsx").expect("the panel's window").id;
assert!(h.state().ui.dock.is_docked(PanelKind::ScriptPanel(panel)), "the panel docks");
click(&mut h, &format!("scriptui.{panel}.pick"));
assert_eq!(*asked.lock().unwrap(), [vec!["srt".to_string()]], "the panel's button opens the file dialog");
let status = h.state().session.script_ui.window(panel).and_then(|w| w.root.lookup(&json!("status"))).map(|w| w.text.clone()).unwrap_or_default();
assert_eq!(status, "Episode 1.srt");
}
+9 -1
View File
@@ -688,7 +688,15 @@ Scripts that build ScriptUI windows publish them to the session; agents drive th
A dialog's `show()` waits for the user: the `script.run` / `file.runScript` reply carries
`"waiting": true`, and the script continues (its final output arrives in the reply of the click
that closes the dialog). File ▸ Scripts: `file.scripts.list`, `file.runScript {"name": …}`,
that closes the dialog). A script's file dialog (`File.openDialog`, `File.saveDialog`,
`Folder.selectDialog`, `openDlg` / `saveDlg` / `selectDlg`, as a Browse… button calls them) waits
the same way in the app, which shows it. `scriptui.fileDialogs` lists the dialogs scripts wait on
(`{id, host, kind: open|save|folder, prompt, exts, label, any, many, start, shown}`; `shown`: the
app has shown it) and `scriptui.fileDialog {"id": …, "paths": […]}` (or `null`: cancelled) answers
one. On Windows the system dialog blocks the app's window until a person closes it, so an agent
can't answer it there; on macOS and Linux it doesn't block. The script's windows refuse events
meanwhile, except `scriptui.close`, which cancels the file dialog first. Without the app (headless
runs), in the Script Console and in Shutdown scripts these return `null` at once. File ▸ Scripts: `file.scripts.list`, `file.runScript {"name": …}`,
`file.installScript` / `file.installScriptUIPanel {"path": …}`, `window.scriptPanel {"name": …}`,
`window.restoreScriptPanels` (the panels open when the app last quit), `file.runStartupScripts` and
`file.runShutdownScripts` (the scripts in `Scripts/Startup` and `Scripts/Shutdown`; the second closes
+1 -1
View File
@@ -20,7 +20,7 @@ our own scripts; no real-world script library has been run against both apps.
| Expression performance | Cached, multi-frame | Per-thread boa contexts | unknown | No benchmark |
| Scripting object model | `app`, `Project`, items, layers, properties, keys, eases, render queue, `TextDocument`, `Shape`, markers, `File`/`Folder`, `Socket`, `app.settings` | Same classes, edits run through undoable engine commands; match names table, the properties of Offset Paths and Zig Zag included; layers, groups and properties are callable (`layer("Effects")(1)` is `.property(...)`) | good | `crates/script` tests (≈ 10 test files) |
| `$.evalFile`, `BridgeTalk` | Evaluate another script file; identify the host application and message other Adobe applications | `$.evalFile` evaluates a file relative to the calling file (nested at most 32 deep, under the scripts' file gate) and returns its last value; `BridgeTalk` names the host honestly (`appName` `effectcraft`, its version); messaging other applications throws "not supported" | partial | `tests_evalfile.rs` (#760); no inter-application messaging |
| ScriptUI | Dialogs, palettes, dockable panels, resource strings, `onDraw` / ScriptUIGraphics, mouse events | Same, dockable panels reopen at launch; a docked panel gets its dock's size and `onResize` (`scriptui.resize`, #2585); a drag keeps reaching the control it started on past the window edge, and `MouseEvent.buttons` reports the held buttons (#2584) | good | `ui_scriptui`, `tests_ui*` |
| ScriptUI | Dialogs, palettes, dockable panels, resource strings, `onDraw` / ScriptUIGraphics, mouse events | Same, dockable panels reopen at launch; a docked panel gets its dock's size and `onResize` (`scriptui.resize`, #2585); a drag keeps reaching the control it started on past the window edge, and `MouseEvent.buttons` reports the held buttons (#2584); `File.openDialog`, `File.saveDialog` and `Folder.selectDialog` (a Browse… button) show the app's file dialog and the script waits for it (#2778) | good | `ui_scriptui`, `tests_ui*` |
| `app.scheduleTask` / `cancelTask` | One-shot and repeating tasks (polling, panel refresh) until `cancelTask` | Same: repeating tasks run every `delay` ms (at least 50 ms, at most 64 pending per script) until `cancelTask`, until they throw (reported once, then cancelled), or until their owner goes: a script's last window closing, or the project closing for scripts without windows (a Startup script's tasks go on until EffectCraft quits); frontends tick them every frame, agents with `script.runTasks` | good | `tests_tasks.rs` (#773); one-shot tasks of a script file still run right after it, not after their delay |
| Scripts menu, ScriptUI Panels folder | yes | yes; a subfolder (one level) of either folder is a submenu named after it | same | [plugins.md](plugins.md) |
| Startup / Shutdown folders | yes | `Scripts/Startup` runs at launch and `Scripts/Shutdown` runs as the desktop app quits, after the project is closed, each in alphabetical order | partial | `crates/script/src/tests/startup.rs`; each script has its own global scope, so a Startup script's variables and functions are not available to later scripts ([plugins.md](plugins.md)) |