diff --git a/apps/effectcraft/src/file_dialogs.rs b/apps/effectcraft/src/file_dialogs.rs index 9f3114367..c8cf5181a 100644 --- a/apps/effectcraft/src/file_dialogs.rs +++ b/apps/effectcraft/src/file_dialogs.rs @@ -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, 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) -> Vec { 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 { + 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 { + 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 { + let all = + |files: Option>| -> Vec { files.unwrap_or_default().into_iter().map(|p| p.to_string_lossy().to_string()).collect() }; + let one = |file: Option| 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) -> Vec { 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) }) diff --git a/crates/automation/src/confine.rs b/crates/automation/src/confine.rs index 70586b798..803317795 100644 --- a/crates/automation/src/confine.rs +++ b/crates/automation/src/confine.rs @@ -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", diff --git a/crates/automation/src/tests.rs b/crates/automation/src/tests.rs index afee15936..a21248cb5 100644 --- a/crates/automation/src/tests.rs +++ b/crates/automation/src/tests.rs @@ -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}"); diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 8c14e03ec..510efd12c 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -430,7 +430,12 @@ fn run_startup(s: &mut Session, _: &Value) -> Result { /// (frontends call it as the app quits, after the unsaved-changes prompt). fn run_shutdown(s: &mut Session, _: &Value) -> Result { 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 ▸ ``: run the panel script (or bring its panel forward). @@ -599,6 +604,21 @@ pub fn specs() -> Vec { 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 + ), ] } diff --git a/crates/engine/src/scriptui.rs b/crates/engine/src/scriptui.rs index 69e572ec2..250ca86bc 100644 --- a/crates/engine/src/scriptui.rs +++ b/crates/engine/src/scriptui.rs @@ -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, + /// 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; @@ -491,6 +535,13 @@ pub struct ScriptUi { /// replaced, until EffectCraft quits. #[serde(skip)] pub startup_hosts: Vec, + /// The file dialogs scripts wait on, until `scriptui.fileDialog` answers them. + pub file_dialogs: Vec, + /// 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 { 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 { + 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 { + 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 = 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::>>().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 { 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 }) } diff --git a/crates/script/src/prelude.js b/crates/script/src/prelude.js index f33da7091..6f31ec37c 100644 --- a/crates/script/src/prelude.js +++ b/crates/script/src/prelude.js @@ -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; } }); diff --git a/crates/script/src/runtime.rs b/crates/script/src/runtime.rs index 28e490158..ab7e511e5 100644 --- a/crates/script/src/runtime.rs +++ b/crates/script/src/runtime.rs @@ -562,7 +562,7 @@ pub(crate) fn new_context() -> Result { 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); 11] = [ + let natives: [(JsString, usize, fn(&JsValue, &[JsValue], &mut Context) -> JsResult); 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 { (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())?; diff --git a/crates/script/src/tests/startup.rs b/crates/script/src/tests/startup.rs index 67da833c5..079bed416 100644 --- a/crates/script/src/tests/startup.rs +++ b/crates/script/src/tests/startup.rs @@ -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()); +} diff --git a/crates/script/src/tests/ui.rs b/crates/script/src/tests/ui.rs index 460376ac5..52bc0b922 100644 --- a/crates/script/src/tests/ui.rs +++ b/crates/script/src/tests/ui.rs @@ -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("")); +} diff --git a/crates/script/src/ui.rs b/crates/script/src/ui.rs index ecf4cd28b..6030ae71e 100644 --- a/crates/script/src/ui.rs +++ b/crates/script/src/ui.rs @@ -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 { + const MAX_EXTS: usize = 64; + const MAX_LEN: usize = 16; + let mut out: Vec = 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 { + 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 { + 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 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)); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index f1373607d..ae0fbf38d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -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 { diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 8eef34d4b..59c12267c 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -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); diff --git a/crates/ui-egui/src/app/gpu.rs b/crates/ui-egui/src/app/gpu.rs index 92ea7665c..96a24c5e0 100644 --- a/crates/ui-egui/src/app/gpu.rs +++ b/crates/ui-egui/src/app/gpu.rs @@ -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); } } diff --git a/crates/ui-egui/src/hooks.rs b/crates/ui-egui/src/hooks.rs index 7a87eeb6c..177084a46 100644 --- a/crates/ui-egui/src/hooks.rs +++ b/crates/ui-egui/src/hooks.rs @@ -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, 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, 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>, + /// 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 Vec>>, /// 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>)>>, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5d49d397b..1d39857df 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -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); } diff --git a/crates/ui-egui/src/lifecycle_tests.rs b/crates/ui-egui/src/lifecycle_tests.rs index 5b97b1961..fe9041987 100644 --- a/crates/ui-egui/src/lifecycle_tests.rs +++ b/crates/ui-egui/src/lifecycle_tests.rs @@ -356,6 +356,39 @@ fn image(width: usize, height: usize) -> Arc { 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(); diff --git a/crates/ui-egui/src/panels/scriptui_view.rs b/crates/ui-egui/src/panels/scriptui_view.rs index 2e34757bf..4b365afdf 100644 --- a/crates/ui-egui/src/panels/scriptui_view.rs +++ b/crates/ui-egui/src/panels/scriptui_view.rs @@ -540,6 +540,115 @@ fn perform(app: &mut EffectcraftApp, ctx: &egui::Context, acts: Vec) { } } +/// 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, + answer: Option, +} + +impl PendingAnswer { + fn send(mut self, paths: Result, 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 = 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, ¶ms, 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) { + 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 = app.session.script_ui.windows.iter().filter(|w| w.kind != WindowKind::Panel).cloned().collect(); diff --git a/crates/ui-egui/tests/it/ui_scriptui.rs b/crates/ui-egui/tests/it/ui_scriptui.rs index a905ebc5a..6c46e71cf 100644 --- a/crates/ui-egui/tests/it/ui_scriptui.rs +++ b/crates/ui-egui/tests/it/ui_scriptui.rs @@ -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>>> = 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::)); + 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>> = 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>> = 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::>(); + 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 ▸ ): 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>>> = 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"); +} diff --git a/docs/agents.md b/docs/agents.md index a83432f04..e09a94957 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -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 diff --git a/docs/scripting-parity.md b/docs/scripting-parity.md index 9aa6ca626..662472c96 100644 --- a/docs/scripting-parity.md +++ b/docs/scripting-parity.md @@ -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)) |