mirror of
https://github.com/storytold/effectcraft.git
synced 2026-11-28 17:19:14 +01:00
Merge branch 'main' into fix/issue-3808-interpret-footage-target
This commit is contained in:
468 files changed
+41174
-7264
No files matched your search
@@ -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; } });
|
||||
|
||||
@@ -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())?;
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -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
@@ -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));
|
||||
|
||||
Reference in new issue
Block a user