Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

#260: file dialogs on Linux no longer stop the app

MrCloudy2059376af1c3a
diff --git a/apps/filmcraft/src/main.rs b/apps/filmcraft/src/main.rs
index 18fb4d7b0..2b1898a08 100644
--- a/apps/filmcraft/src/main.rs
+++ b/apps/filmcraft/src/main.rs
@@ -226,6 +226,13 @@ fn main() -> eframe::Result {
app.hooks.pick_folder = Some(Box::new(|| rfd::FileDialog::new().pick_folder().map(|p| p.to_string_lossy().to_string())));
app.hooks.pick_folder_at =
Some(Box::new(|dir: &str| rfd::FileDialog::new().set_directory(dir).pick_folder().map(|p| p.to_string_lossy().into_owned())));
+ // Linux: the XDG portal call blocks until the user chooses, which would stop the frame
+ // loop (GNOME offers to force-quit the window after about five seconds, #260). Show the
+ // dialog on its own thread instead; the app keeps running and acts on the answer.
+ #[cfg(target_os = "linux")]
+ {
+ app.hooks.run_dialog = Some(Box::new(run_dialog_off_thread));
+ }
app.hooks.open_path = Some(Box::new(open_path));
// Settings ▸ General ▸ Interface Language ▸ System Language (#218).
app.hooks.system_languages = Some(Box::new(|| sys_locale::get_locales().collect()));
@@ -321,6 +328,60 @@ fn agent_event_loop(agent: bool) -> Option<eframe::EventLoopBuilderHook> {
None
}
+/// Show `dialog` with rfd on a worker thread and answer on the returned channel (#260). Filter
+/// names are translated here, on the UI thread (the interface language is per thread). A dialog
+/// thread that can't start or panics drops the sender: the app takes that as cancelled.
+#[cfg(target_os = "linux")]
+fn run_dialog_off_thread(dialog: filmcraft_ui_egui::native_dialogs::FileDialog) -> std::sync::mpsc::Receiver<Vec<String>> {
+ use filmcraft_ui_egui::native_dialogs::FileDialog;
+ let t = |s: &str| filmcraft_ui_egui::i18n::t(s).to_string();
+ let media = t("Media");
+ let project = t("FilmCraft Project");
+ let dialog = match dialog {
+ FileDialog::OpenFile { filter, exts } => FileDialog::OpenFile { filter: t(&filter), exts },
+ FileDialog::SaveAs { filter, exts, name } => FileDialog::SaveAs { filter: t(&filter), exts, name },
+ other => other,
+ };
+ let (tx, rx) = std::sync::mpsc::channel();
+ let spawned = std::thread::Builder::new().name("file-dialog".into()).spawn(move || {
+ let shown = std::panic::catch_unwind(move || {
+ let path = |p: std::path::PathBuf| p.to_string_lossy().into_owned();
+ match dialog {
+ FileDialog::OpenFiles { exts } => {
+ rfd::FileDialog::new().add_filter(&media, &exts).pick_files().unwrap_or_default().into_iter().map(path).collect()
+ }
+ FileDialog::OpenFile { filter, exts } => rfd::FileDialog::new().add_filter(&filter, &exts).pick_file().map(path).into_iter().collect(),
+ FileDialog::Relink { exts, .. } => rfd::FileDialog::new().add_filter(&media, &exts).pick_file().map(path).into_iter().collect(),
+ FileDialog::OpenProject => rfd::FileDialog::new().add_filter(&project, &["fcproj"]).pick_file().map(path).into_iter().collect(),
+ FileDialog::SaveProject { name } => {
+ rfd::FileDialog::new().add_filter(&project, &["fcproj"]).set_file_name(name).save_file().map(path).into_iter().collect()
+ }
+ FileDialog::SaveAs { filter, exts, name } => {
+ rfd::FileDialog::new().add_filter(&filter, &exts).set_file_name(name).save_file().map(path).into_iter().collect()
+ }
+ FileDialog::Folder { at } => {
+ let d = rfd::FileDialog::new();
+ let d = match at {
+ Some(dir) if !dir.is_empty() => d.set_directory(dir),
+ _ => d,
+ };
+ d.pick_folder().map(path).into_iter().collect::<Vec<_>>()
+ }
+ }
+ });
+ match shown {
+ Ok(paths) => {
+ let _ = tx.send(paths);
+ }
+ Err(_) => log::warn!("the file dialog thread panicked; taken as cancelled"),
+ }
+ });
+ if let Err(e) = spawned {
+ log::warn!("could not start the file dialog thread: {e}");
+ }
+ rx
+}
+
#[cfg(test)]
mod tests {
/// Start-up registers the hardware decoders whether or not anything is logged (no logger is
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index a39dc82ea..0ab5f90ba 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -801,6 +801,7 @@
Relink others automatically Volver a vincular los demás automáticamente
Search in: Buscar en:
Browse… Examinar…
+ A file dialog is already open Ya hay un cuadro de diálogo de archivos abierto
Exact name matches only Solo coincidencias exactas de nombre
No candidates yet — Search a folder or Locate the file. Aún no hay candidatos: busca en una carpeta o localiza el archivo.
✔ same file ✔ mismo archivo
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 83d18261e..d1ec22566 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -42,6 +42,7 @@ pub mod i18n;
pub mod icons;
pub mod links;
pub mod menus;
+pub mod native_dialogs;
pub mod panels;
pub mod perf;
#[cfg(not(target_arch = "wasm32"))]
@@ -63,6 +64,7 @@ use serde_json::{Value, json};
pub use control::ControlRequest;
use dock::PanelKind;
use frames::{FrameKey, FrameServer, Target};
+use native_dialogs::FileDialog;
use state::UiState;
use theme::{ThemeKind, Tokens};
@@ -131,6 +133,11 @@ pub struct HostHooks {
/// Open a file in its default application, or (`true`) reveal it in the file manager (Edit ▸
/// Edit Original, Help ▸ Reveal Log Files).
pub open_path: Option<Box<dyn FnMut(&str, bool) -> Result<(), String>>>,
+ /// Show a file dialog without blocking the UI thread and answer on the returned channel with
+ /// the chosen paths (none: cancelled). With it, [`FilmcraftApp::pick`] keeps the frame loop
+ /// running while the dialog is open (the desktop app on Linux, #260); without it the
+ /// synchronous pickers above are used.
+ pub run_dialog: Option<Box<dyn FnMut(native_dialogs::FileDialog) -> Receiver<Vec<String>>>>,
}
/// The command a [`HostHooks::pick_file_for_relink`] caller runs with the chosen file, for hosts
@@ -226,6 +233,8 @@ pub struct FilmcraftApp {
pub hooks: HostHooks,
pub dialog: Option<Dialog>,
pub file_dialogs: panels::file_dialogs::FileDialogState,
+ /// The native file dialog the host is showing ([`Self::pick`]).
+ native_dialog: Option<native_dialogs::PendingDialog>,
pub auto: automation::Registry,
/// Named textures (monitors, thumbnails) with the key they show.
textures: HashMap<String, (FrameKey, TextureHandle)>,
@@ -430,6 +439,7 @@ impl FilmcraftApp {
// Unsaved changes left by a session that died are offered first thing.
dialog: recovery.then_some(Dialog::Recovery),
file_dialogs: Default::default(),
+ native_dialog: None,
auto: Default::default(),
textures: HashMap::new(),
control_rx: None,
@@ -1032,65 +1042,69 @@ impl FilmcraftApp {
.chain(&["srt", "vtt", "scc", "edl", "xml", "fcpxml", "otio", "aaf", "omf"])
.copied()
.collect();
- let paths = self.hooks.pick_files.as_mut().map(|f| f(&exts)).unwrap_or_default();
- if paths.is_empty() {
- return Ok(Value::Null);
- }
- let bin = params.get("bin").cloned().unwrap_or_else(|| json!(self.import_bin().0));
- let r = self.session.execute("file.import", json!({"paths": paths, "bin": bin})).map_err(|e| e.to_string());
- if let Ok(v) = &r
- && let Some(errs) = v.get("errors").and_then(Value::as_array)
- && !errs.is_empty()
- {
- self.ui.status = errs.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("; ");
- }
- r
+ let bin = params.get("bin").cloned();
+ self.pick(FileDialog::open_files(&exts), move |app, paths| {
+ if paths.is_empty() {
+ return Ok(Value::Null);
+ }
+ let bin = bin.unwrap_or_else(|| json!(app.import_bin().0));
+ let r = app.session.execute("file.import", json!({"paths": paths, "bin": bin})).map_err(|e| e.to_string());
+ if let Ok(v) = &r
+ && let Some(errs) = v.get("errors").and_then(Value::as_array)
+ && !errs.is_empty()
+ {
+ app.ui.status = errs.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("; ");
+ }
+ r
+ })
}
// File ▸ Import with Image Sequence: choose the first numbered still
- "file.importImageSequence" => {
- let paths = self.hooks.pick_files.as_mut().map(|f| f(filmcraft_media::STILL_EXTENSIONS)).unwrap_or_default();
+ "file.importImageSequence" => self.pick(FileDialog::open_files(filmcraft_media::STILL_EXTENSIONS), |app, paths| {
let Some(path) = paths.into_iter().next() else { return Ok(Value::Null) };
- let r = self.session.execute("file.importImageSequence", json!({"path": path})).map_err(|e| e.to_string());
+ let r = app.session.execute("file.importImageSequence", json!({"path": path})).map_err(|e| e.to_string());
if let Err(e) = &r {
- self.ui.status = e.clone();
+ app.ui.status = e.clone();
}
r
- }
+ }),
"file.saveAs" | "file.save" | "file.saveCopy" => {
let suggested =
if id == "file.saveCopy" { format!("{} copy.fcproj", self.session.project.name) } else { format!("{}.fcproj", self.session.project.name) };
- let Some(path) = self.hooks.pick_save.as_mut().and_then(|f| f(&suggested)) else { return Ok(Value::Null) };
let cmd = if id == "file.saveCopy" { "file.saveCopy" } else { "file.saveAs" };
- self.session.execute(cmd, json!({"path": path})).map_err(|e| e.to_string())
- }
- "file.open" => {
- let Some(path) = self.hooks.pick_open_project.as_mut().and_then(|f| f()) else { return Ok(Value::Null) };
- self.session.execute("file.open", json!({"path": path})).map_err(|e| e.to_string())
+ self.pick(FileDialog::SaveProject { name: suggested }, move |app, paths| {
+ let Some(path) = paths.into_iter().next() else { return Ok(Value::Null) };
+ app.session.execute(cmd, json!({"path": path})).map_err(|e| e.to_string())
+ })
}
+ "file.open" => self.pick(FileDialog::OpenProject, |app, paths| {
+ let Some(path) = paths.into_iter().next() else { return Ok(Value::Null) };
+ app.session.execute("file.open", json!({"path": path})).map_err(|e| e.to_string())
+ }),
"graphics.newFromFile" => {
let exts: Vec<&str> = filmcraft_media::STILL_EXTENSIONS.iter().chain(filmcraft_media::VIDEO_EXTENSIONS).copied().collect();
- let paths = self.hooks.pick_files.as_mut().map(|f| f(&exts)).unwrap_or_default();
- let Some(path) = paths.into_iter().next() else { return Ok(Value::Null) };
- self.session.execute("graphics.newFromFile", json!({"path": path})).map_err(|e| e.to_string())
+ self.pick(FileDialog::open_files(&exts), |app, paths| {
+ let Some(path) = paths.into_iter().next() else { return Ok(Value::Null) };
+ app.session.execute("graphics.newFromFile", json!({"path": path})).map_err(|e| e.to_string())
+ })
}
- "captions.import" => {
- let paths = self.hooks.pick_files.as_mut().map(|f| f(&["srt", "vtt", "scc", "mcc", "stl", "ttml", "dfxp", "xml"])).unwrap_or_default();
+ "captions.import" => self.pick(FileDialog::open_files(&["srt", "vtt", "scc", "mcc", "stl", "ttml", "dfxp", "xml"]), |app, paths| {
let Some(path) = paths.into_iter().next() else { return Ok(Value::Null) };
- self.session.execute("captions.import", json!({"path": path})).map_err(|e| e.to_string())
- }
+ app.session.execute("captions.import", json!({"path": path})).map_err(|e| e.to_string())
+ }),
"captions.export" => {
let name = self.session.state.active_sequence.and_then(|s| self.session.project.item(s)).map(|i| i.name.clone()).unwrap_or_default();
let suggested = format!("{}.srt", name.replace(' ', "_"));
- let Some(path) =
- self.hooks.pick_save_as.as_mut().and_then(|f| {
- f("Captions (SRT, WebVTT, SCC, MCC, EBU STL, TTML, DFXP)", &["srt", "vtt", "scc", "mcc", "stl", "ttml", "dfxp"], &suggested)
- })
- else {
- return Ok(Value::Null);
- };
+ let dialog = FileDialog::save_as(
+ "Captions (SRT, WebVTT, SCC, MCC, EBU STL, TTML, DFXP)",
+ &["srt", "vtt", "scc", "mcc", "stl", "ttml", "dfxp"],
+ &suggested,
+ );
let mut p = params.clone();
- p["path"] = json!(path);
- self.session.execute("captions.export", p).map_err(|e| e.to_string())
+ self.pick(dialog, move |app, paths| {
+ let Some(path) = paths.into_iter().next() else { return Ok(Value::Null) };
+ p["path"] = json!(path);
+ app.session.execute("captions.export", p).map_err(|e| e.to_string())
+ })
}
_ => match EXPORT_SAVE_DIALOGS.iter().find(|(c, ..)| *c == id) {
Some(&(_, filter, ext)) => self.export_save_dialog(id, filter, ext, params),
@@ -1103,9 +1117,9 @@ impl FilmcraftApp {
/// run the command with that `path` and the rest of `params`.
fn export_save_dialog(&mut self, id: &str, filter: &str, ext: &str, params: &Value) -> Result<Value, String> {
filmcraft_engine::find_command(id).map_or(Ok(()), |c| (c.enabled)(&self.session))?;
- let Some(pick) = self.hooks.pick_save_as.as_mut() else {
+ if !FileDialog::save_as(filter, &[ext], "").available(&self.hooks) {
return Err("no save dialog available: run the command with a `path`".into());
- };
+ }
// Timelines are named after the sequence; a selection must not suggest the open project's file.
let sequence = self.session.state.active_sequence.and_then(|s| self.session.project.item(s)).map(|i| i.name.clone());
let stem = match id {
@@ -1115,15 +1129,18 @@ impl FilmcraftApp {
};
let stem: String = stem.chars().map(|c| if matches!(c, '/' | '\\') || c.is_control() { '-' } else { c }).collect();
let stem = if stem.trim().is_empty() { "Untitled".to_string() } else { stem };
- let Some(path) = pick(filter, &[ext], &format!("{stem}.{ext}")) else { return Ok(Value::Null) };
let mut p = params.as_object().cloned().unwrap_or_default();
- p.insert("path".into(), json!(path));
- let r = self.session.execute(id, Value::Object(p)).map_err(|e| e.to_string());
- self.ui.status = match &r {
- Ok(_) => tlf!("Exported {path}", path),
- Err(e) => e.clone(),
- };
- r
+ let id = id.to_string();
+ self.pick(FileDialog::save_as(filter, &[ext], &format!("{stem}.{ext}")), move |app, paths| {
+ let Some(path) = paths.into_iter().next() else { return Ok(Value::Null) };
+ p.insert("path".into(), json!(path));
+ let r = app.session.execute(&id, Value::Object(p)).map_err(|e| e.to_string());
+ app.ui.status = match &r {
+ Ok(_) => tlf!("Exported {path}", path),
+ Err(e) => e.clone(),
+ };
+ r
+ })
}
/// Import dropped files.
@@ -1608,6 +1625,8 @@ impl eframe::App for FilmcraftApp {
}
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
+ // a native file dialog's answer first, so the panels draw what it chose (#260)
+ self.poll_native_dialog(ctx);
if !self.styled {
theme::install(ctx, &self.tokens);
// theme::install replaces the fonts: add the system Japanese font back (or fall back to
diff --git a/crates/ui-egui/src/native_dialogs.rs b/crates/ui-egui/src/native_dialogs.rs
new file mode 100644
index 000000000..a18ae8bf8
--- /dev/null
+++ b/crates/ui-egui/src/native_dialogs.rs
@@ -0,0 +1,181 @@
+//! Native file dialogs that don't stop the frame loop (#260).
+//!
+//! A dialog is asked for with [`FilmcraftApp::pick`]: what to show ([`FileDialog`]) and what to do
+//! with the chosen paths. A host that can show dialogs without blocking ([`HostHooks::run_dialog`]:
+//! the desktop app on Linux, where the XDG portal call would otherwise hold the UI thread until the
+//! user chooses, and GNOME offers to force-quit the window after about five seconds) gets the
+//! dialog and answers on a channel; the frame loop keeps running, and the continuation runs on the
+//! frame the answer arrives ([`FilmcraftApp::poll_native_dialog`]). Without it the host's
+//! synchronous pickers (`pick_files`, `pick_save_as`, …) are called and the continuation runs at
+//! once, as before: headless tests, the control channel's stand-ins and other hosts are unchanged.
+//!
+//! Two entry points:
+//! - [`FilmcraftApp::pick`] for menu and control-channel commands: with the synchronous pickers
+//! the continuation runs at once and its result is the command's (agents and tests see what
+//! they saw before); with the runner the command answers `{"dialog": "open"}`.
+//! - [`FilmcraftApp::pick_ui`] for a panel's Browse… / Import… / Export… button: the continuation
+//! always runs at the start of a later frame, before the panels draw, since a panel works on a
+//! copy of its state that it writes back at the end of the frame. It writes into the dialog's
+//! stored state (`app.ui.…`, an egui temporary); when the user has closed that dialog meanwhile
+//! there is nothing to write into and the path is dropped.
+//!
+//! One dialog is open at a time; asking for another one meanwhile is refused.
+
+use std::sync::mpsc::{Receiver, TryRecvError};
+use std::time::Duration;
+
+use serde_json::{Value, json};
+
+use crate::{FilmcraftApp, HostHooks, RelinkHint};
+
+/// A native file dialog. Filters are a name and extensions without dots.
+#[derive(Clone, Debug)]
+pub enum FileDialog {
+ /// Choose one or more files (File ▸ Import; one file where only the first is used).
+ OpenFiles { exts: Vec<String> },
+ /// Choose one file.
+ OpenFile { filter: String, exts: Vec<String> },
+ /// Choose a FilmCraft project to open.
+ OpenProject,
+ /// Save a FilmCraft project, suggesting `name`.
+ SaveProject { name: String },
+ /// Save a file, suggesting `name`.
+ SaveAs { filter: String, exts: Vec<String>, name: String },
+ /// Choose a folder, starting at `at` when there is one.
+ Folder { at: Option<String> },
+ /// Choose one file to relink to (Link Media ▸ Locate…, Attach Proxies, Reconnect Full
+ /// Resolution): the host's relink picker, which may take over the command (the web).
+ Relink { exts: Vec<String>, hint: RelinkHint },
+}
+
+/// What to do with the chosen paths (none: cancelled). Its result is the request's (control
+/// channel, menu) when the dialog answers at once; otherwise an error goes to the status line.
+pub(crate) type Continuation = Box<dyn FnOnce(&mut FilmcraftApp, Vec<String>) -> Result<Value, String>>;
+
+/// The dialog a host is showing, and what to do with its answer.
+pub(crate) struct PendingDialog {
+ answer: Receiver<Vec<String>>,
+ then: Continuation,
+}
+
+fn strings(v: &[&str]) -> Vec<String> {
+ v.iter().map(|s| (*s).to_string()).collect()
+}
+
+impl FileDialog {
+ pub fn open_files(exts: &[&str]) -> Self {
+ Self::OpenFiles { exts: strings(exts) }
+ }
+ pub fn open_file(filter: &str, exts: &[&str]) -> Self {
+ Self::OpenFile { filter: filter.to_string(), exts: strings(exts) }
+ }
+ pub fn save_as(filter: &str, exts: &[&str], name: &str) -> Self {
+ Self::SaveAs { filter: filter.to_string(), exts: strings(exts), name: name.to_string() }
+ }
+
+ /// Whether `hooks` can show this dialog at all (a host without the picker leaves it out).
+ pub fn available(&self, hooks: &HostHooks) -> bool {
+ hooks.run_dialog.is_some()
+ || match self {
+ Self::OpenFiles { .. } => hooks.pick_files.is_some(),
+ Self::OpenFile { .. } => hooks.pick_open_file.is_some(),
+ Self::OpenProject => hooks.pick_open_project.is_some(),
+ Self::SaveProject { .. } => hooks.pick_save.is_some(),
+ Self::SaveAs { .. } => hooks.pick_save_as.is_some(),
+ Self::Folder { at } => hooks.pick_folder.is_some() || (at.is_some() && hooks.pick_folder_at.is_some()),
+ Self::Relink { .. } => hooks.pick_file_for_relink.is_some() || hooks.pick_files.is_some(),
+ }
+ }
+
+ /// Show the dialog with the host's synchronous pickers, as before #260.
+ fn run_now(self, hooks: &mut HostHooks) -> Vec<String> {
+ let one = |p: Option<String>| p.into_iter().collect::<Vec<_>>();
+ match self {
+ Self::OpenFiles { exts } => hooks.pick_files.as_mut().map(|f| f(&refs(&exts))).unwrap_or_default(),
+ Self::OpenFile { filter, exts } => one(hooks.pick_open_file.as_mut().and_then(|f| f(&filter, &refs(&exts)))),
+ Self::OpenProject => one(hooks.pick_open_project.as_mut().and_then(|f| f())),
+ Self::SaveProject { name } => one(hooks.pick_save.as_mut().and_then(|f| f(&name))),
+ Self::SaveAs { filter, exts, name } => one(hooks.pick_save_as.as_mut().and_then(|f| f(&filter, &refs(&exts), &name))),
+ Self::Folder { at } => one(match (at, hooks.pick_folder_at.as_mut()) {
+ (Some(dir), Some(f)) => f(&dir),
+ _ => hooks.pick_folder.as_mut().and_then(|f| f()),
+ }),
+ Self::Relink { exts, hint } => match hooks.pick_file_for_relink.as_mut() {
+ Some(f) => one(f(&refs(&exts), Some(hint))),
+ None => hooks.pick_files.as_mut().map(|f| f(&refs(&exts))).unwrap_or_default().into_iter().take(1).collect(),
+ },
+ }
+ }
+}
+
+fn refs(v: &[String]) -> Vec<&str> {
+ v.iter().map(String::as_str).collect()
+}
+
+impl FilmcraftApp {
+ /// Show `dialog`, then call `then` with the chosen paths (empty when cancelled). With a host
+ /// that shows dialogs without blocking, this returns `{"dialog": "open"}` and `then` runs on a
+ /// later frame; otherwise `then` runs now and its result is returned. While a dialog is open
+ /// another one is refused.
+ pub fn pick(&mut self, dialog: FileDialog, then: impl FnOnce(&mut FilmcraftApp, Vec<String>) -> Result<Value, String> + 'static) -> Result<Value, String> {
+ if self.native_dialog.is_some() {
+ return Err(tl!("A file dialog is already open").into());
+ }
+ if let Some(run) = self.hooks.run_dialog.as_mut() {
+ self.native_dialog = Some(PendingDialog { answer: run(dialog), then: Box::new(then) });
+ return Ok(json!({"dialog": "open"}));
+ }
+ let paths = dialog.run_now(&mut self.hooks);
+ then(self, paths)
+ }
+
+ /// [`Self::pick`] for a panel's button: `then` returns nothing, and a refusal (another dialog is
+ /// open) goes to the status line. `then` always runs at the start of a later frame, also with
+ /// the host's synchronous pickers: a panel works on a copy of its state and writes it back at
+ /// the end of the frame, which would overwrite a path written in the middle of it.
+ pub fn pick_ui(&mut self, dialog: FileDialog, then: impl FnOnce(&mut FilmcraftApp, Vec<String>) + 'static) {
+ if self.native_dialog.is_some() {
+ self.ui.status = tl!("A file dialog is already open").into();
+ return;
+ }
+ let answer = match self.hooks.run_dialog.as_mut() {
+ Some(run) => run(dialog),
+ None => {
+ let (tx, rx) = std::sync::mpsc::channel();
+ // the receiver is alive (held here): sending can't fail
+ let _ = tx.send(dialog.run_now(&mut self.hooks));
+ rx
+ }
+ };
+ let then: Continuation = Box::new(move |app, paths| {
+ then(app, paths);
+ Ok(Value::Null)
+ });
+ self.native_dialog = Some(PendingDialog { answer, then });
+ }
+
+ /// Whether a file dialog is open (one the host shows without blocking).
+ pub fn native_dialog_open(&self) -> bool {
+ self.native_dialog.is_some()
+ }
+
+ /// Run the open dialog's continuation once it has answered (called first thing every frame).
+ /// While it is open the frame loop keeps polling at a low rate.
+ pub(crate) fn poll_native_dialog(&mut self, ctx: &egui::Context) {
+ let Some(pending) = &self.native_dialog else { return };
+ let paths = match pending.answer.try_recv() {
+ Ok(paths) => paths,
+ Err(TryRecvError::Empty) => {
+ ctx.request_repaint_after(Duration::from_millis(100));
+ return;
+ }
+ // the host's dialog ended without an answer (its thread failed): as if cancelled
+ Err(TryRecvError::Disconnected) => Vec::new(),
+ };
+ let Some(pending) = self.native_dialog.take() else { return };
+ if let Err(e) = (pending.then)(self, paths) {
+ self.ui.status = e;
+ }
+ ctx.request_repaint();
+ }
+}
diff --git a/crates/ui-egui/src/panels/export_mode.rs b/crates/ui-egui/src/panels/export_mode.rs
index 4838ce5ff..46570ec86 100644
--- a/crates/ui-egui/src/panels/export_mode.rs
+++ b/crates/ui-egui/src/panels/export_mode.rs
@@ -31,6 +31,7 @@ use serde_json::{Value, json};
use crate::FilmcraftApp;
use crate::frames::{FrameKey, Target};
+use crate::native_dialogs::FileDialog;
use crate::theme::Tokens;
/// Export mode state.
@@ -543,12 +544,20 @@ fn settings_column(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
if open_manager {
app.ui.export.manager = Some(PresetManager { selected: app.ui.export.preset.clone(), ..Default::default() });
}
- if pick_folder && let Some(d) = app.hooks.pick_folder.as_mut().and_then(|f| f()) {
- app.ui.export.location = d;
+ if pick_folder {
+ app.pick_ui(FileDialog::Folder { at: None }, |app, paths| {
+ if let Some(d) = paths.into_iter().next() {
+ app.ui.export.location = d;
+ }
+ });
}
- if pick_overlay && let Some(f) = app.hooks.pick_open_file.as_mut().and_then(|f| f(tl!("Image"), &["png", "jpg", "jpeg"])) {
- app.ui.export.settings.effects.image_overlay.path = f;
- app.ui.export.settings.effects.image_overlay.enabled = true;
+ if pick_overlay {
+ app.pick_ui(FileDialog::open_file(tl!("Image"), &["png", "jpg", "jpeg"]), |app, paths| {
+ if let Some(f) = paths.into_iter().next() {
+ app.ui.export.settings.effects.image_overlay.path = f;
+ app.ui.export.settings.effects.image_overlay.enabled = true;
+ }
+ });
}
reg.flush(app);
}
@@ -1160,22 +1169,25 @@ fn preset_manager(app: &mut FilmcraftApp, ctx: &egui::Context) {
app.ui.status = e.to_string();
}
match pick {
- Some("import") => match app.hooks.pick_open_file.as_mut().and_then(|f| f(tl!("Export presets"), &["json"])) {
+ Some("import") => app.pick_ui(FileDialog::open_file(tl!("Export presets"), &["json"]), |app, paths| match paths.into_iter().next() {
Some(path) => {
if let Err(e) = app.session.execute("export.presets.import", json!({"path": path})) {
app.ui.status = e.to_string();
}
}
None => app.ui.status = tl!("Import: no file chosen (agents: export.presets.import {path})").into(),
- },
- Some(_) => match app.hooks.pick_save_as.as_mut().and_then(|f| f(tl!("Export presets"), &["json"], &format!("{}.json", m.selected))) {
- Some(path) => {
- if let Err(e) = app.session.execute("export.presets.export", json!({"path": path, "names": [m.selected]})) {
- app.ui.status = e.to_string();
+ }),
+ Some(_) => {
+ let selected = m.selected.clone();
+ app.pick_ui(FileDialog::save_as(tl!("Export presets"), &["json"], &format!("{selected}.json")), move |app, paths| match paths.into_iter().next() {
+ Some(path) => {
+ if let Err(e) = app.session.execute("export.presets.export", json!({"path": path, "names": [selected]})) {
+ app.ui.status = e.to_string();
+ }
}
- }
- None => app.ui.status = tl!("Export: no file chosen (agents: export.presets.export {path, names})").into(),
- },
+ None => app.ui.status = tl!("Export: no file chosen (agents: export.presets.export {path, names})").into(),
+ })
+ }
None => {}
}
if let Some(name) = apply
diff --git a/crates/ui-egui/src/panels/frame_export.rs b/crates/ui-egui/src/panels/frame_export.rs
index 4790c440a..b3a8f8dd2 100644
--- a/crates/ui-egui/src/panels/frame_export.rs
+++ b/crates/ui-egui/src/panels/frame_export.rs
@@ -1,4 +1,5 @@
//! Monitor Export Frame settings, with captured target/time and a destination folder.
+use crate::native_dialogs::FileDialog;
use crate::{
FilmcraftApp,
icons::{self, Icon},
@@ -152,7 +153,7 @@ pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {
let r = ui.checkbox(&mut d.import, "Import into project");
elems.push(("exportFrame.import".into(), r.rect, d.import.to_string()));
ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), 26.0), egui::Layout::right_to_left(egui::Align::Center), |ui| {
- let r = ui.add_enabled(app.hooks.pick_folder_at.is_some() || app.hooks.pick_folder.is_some(), egui::Button::new("Browse…"));
+ let r = ui.add_enabled(FileDialog::Folder { at: Some(String::new()) }.available(&app.hooks), egui::Button::new("Browse…"));
browse = r.clicked();
elems.push(("exportFrame.browse".into(), r.rect, "Browse".into()));
});
@@ -211,14 +212,16 @@ pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {
close |= ctx.input(|i| i.key_pressed(egui::Key::Escape));
if browse && !close {
let folder = filmcraft_engine::export_tools::expand_home(d.folder.trim());
- let picked = match app.hooks.pick_folder_at.as_mut() {
- Some(pick) => pick(&folder),
- None => app.hooks.pick_folder.as_mut().and_then(|pick| pick()),
- };
- if let Some(path) = picked {
- d.folder = path;
- d.replace = None;
- }
+ let ctx = ctx.clone();
+ // into the dialog's stored draft, if it is still open when the folder comes back
+ app.pick_ui(FileDialog::Folder { at: Some(folder) }, move |_, paths| {
+ let Some(path) = paths.into_iter().next() else { return };
+ if let Some(Some(mut d)) = ctx.data(|m| m.get_temp::<Option<Draft>>(draft_id())) {
+ d.folder = path;
+ d.replace = None;
+ ctx.data_mut(|m| m.insert_temp(draft_id(), Some(d)));
+ }
+ });
}
if (apply || replace) && !close {
let mut stem = clean(&d.name);
diff --git a/crates/ui-egui/src/panels/graphics_templates.rs b/crates/ui-egui/src/panels/graphics_templates.rs
index d66c346a8..39d29baf8 100644
--- a/crates/ui-egui/src/panels/graphics_templates.rs
+++ b/crates/ui-egui/src/panels/graphics_templates.rs
@@ -29,6 +29,7 @@ use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::FilmcraftApp;
+use crate::native_dialogs::FileDialog;
use crate::theme::Tokens;
/// One candidate property in the Export As Motion Graphics Template dialog.
@@ -589,10 +590,13 @@ pub fn route(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: &Val
let empty = params.as_object().is_none_or(|m| m.is_empty());
match id {
"graphics.template.install" if params.get("path").is_none() => {
- let path = app.hooks.pick_open_file.as_mut().and_then(|f| f(tl!("FilmCraft Graphics Template"), &["fcgt"]))?;
- let r = app.session.execute(id, json!({"path": path})).map_err(|e| e.to_string());
- invalidate(ctx);
- Some(r)
+ let (id, ctx) = (id.to_string(), ctx.clone());
+ Some(app.pick(FileDialog::open_file(tl!("FilmCraft Graphics Template"), &["fcgt"]), move |app, paths| {
+ let Some(path) = paths.into_iter().next() else { return Ok(Value::Null) };
+ let r = app.session.execute(&id, json!({"path": path})).map_err(|e| e.to_string());
+ invalidate(&ctx);
+ r
+ }))
}
"graphics.template.export" | "file.exportGraphicsTemplate" if empty => {
let clip = filmcraft_engine::graphics::target_clip(&app.session, &Value::Null);
diff --git a/crates/ui-egui/src/panels/interchange_export.rs b/crates/ui-egui/src/panels/interchange_export.rs
index 205cdafa9..2426674c6 100644
--- a/crates/ui-egui/src/panels/interchange_export.rs
+++ b/crates/ui-egui/src/panels/interchange_export.rs
@@ -10,6 +10,7 @@
use serde_json::{Value, json};
use crate::FilmcraftApp;
+use crate::native_dialogs::FileDialog;
#[derive(Clone, Debug, PartialEq)]
struct Draft {
@@ -176,8 +177,12 @@ pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {
let (ext, filter) = if d.omf { ("omf", "OMF") } else { ("aaf", "AAF") };
let stem = if d.title.is_empty() { "Sequence".to_string() } else { d.title.replace(['/', '\\', ':'], "_") };
let suggested = format!("{stem}.{ext}");
- match app.hooks.pick_save_as.as_mut().and_then(|f| f(filter, &[ext], &suggested)) {
- Some(path) => {
+ let dialog = FileDialog::save_as(filter, &[ext], &suggested);
+ if dialog.available(&app.hooks) {
+ // the dialog closes now: the export takes its settings as they are
+ let d = d.clone();
+ app.pick_ui(dialog, move |app, paths| {
+ let Some(path) = paths.into_iter().next() else { return };
let mut params = json!({
"path": path,
"breakoutToMono": d.breakout,
@@ -199,9 +204,9 @@ pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {
Ok(v) => app.ui.status = tlf!("Exported {path}", path = v["path"].as_str().unwrap_or_default()),
Err(e) => app.ui.status = e.to_string(),
}
- }
- None if app.hooks.pick_save_as.is_none() => app.ui.status = "no save dialog available: run the command with a `path`".into(),
- None => {}
+ });
+ } else {
+ app.ui.status = "no save dialog available: run the command with a `path`".into();
}
}
ctx.data_mut(|m| m.insert_temp(draft_id(), if close { None } else { Some(d) }));
diff --git a/crates/ui-egui/src/panels/lumetri.rs b/crates/ui-egui/src/panels/lumetri.rs
index ff35ec199..b1ec1c6c3 100644
--- a/crates/ui-egui/src/panels/lumetri.rs
+++ b/crates/ui-egui/src/panels/lumetri.rs
@@ -15,6 +15,7 @@ use serde_json::{Value, json};
use crate::FilmcraftApp;
use crate::icons::{self, Icon};
+use crate::native_dialogs::FileDialog;
use crate::theme::Tokens;
type Actions = Vec<Value>;
@@ -255,8 +256,14 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
continue;
}
if p.get("browse").is_some() {
- let Some(path) = app.hooks.pick_open_file.as_mut().and_then(|f| f(tl!("LUT"), &["cube", "3dl"])) else { continue };
- p = json!({"path": path});
+ let (cmd, clip) = (cmd.to_string(), clip.0);
+ app.pick_ui(FileDialog::open_file(tl!("LUT"), &["cube", "3dl"]), move |app, paths| {
+ let Some(path) = paths.into_iter().next() else { return };
+ if let Err(err) = app.session.execute(&cmd, json!({"path": path, "clip": clip})) {
+ app.ui.status = err.to_string();
+ }
+ });
+ continue;
}
p["clip"] = json!(clip.0);
if let Err(err) = app.session.execute(cmd, p) {
diff --git a/crates/ui-egui/src/panels/media_dialogs.rs b/crates/ui-egui/src/panels/media_dialogs.rs
index e4cd2e93e..5c59fef2f 100644
--- a/crates/ui-egui/src/panels/media_dialogs.rs
+++ b/crates/ui-egui/src/panels/media_dialogs.rs
@@ -17,6 +17,7 @@
use egui::{Color32, RichText};
use serde_json::{Value, json};
+use crate::native_dialogs::FileDialog;
use crate::state::{LinkMediaDraft, ProjectManagerDraft, ProxyDraft};
use crate::{FilmcraftApp, RelinkHint};
@@ -82,15 +83,11 @@ pub fn route(app: &mut FilmcraftApp, id: &str, params: &Value) -> Option<Result<
let Some(item) = item else { return Some(Err("select a clip in the Project panel".into())) };
let exts: Vec<&str> = filmcraft_media::VIDEO_EXTENSIONS.to_vec();
let hint = RelinkHint { command: id.to_string(), params: json!({"item": item.0}) };
- let picked = if let Some(picker) = app.hooks.pick_file_for_relink.as_mut() {
- picker(&exts, Some(hint))
- } else if let Some(picker) = app.hooks.pick_files.as_mut() {
- picker(&exts).into_iter().next()
- } else {
- None
- };
- let Some(picked) = picked else { return Some(Ok(Value::Null)) };
- Some(app.session.execute(id, json!({"item": item.0, "path": picked})).map_err(|e| e.to_string()))
+ let id = id.to_string();
+ Some(app.pick(FileDialog::Relink { exts: exts.iter().map(|e| e.to_string()).collect(), hint }, move |app, paths| {
+ let Some(picked) = paths.into_iter().next() else { return Ok(Value::Null) };
+ app.session.execute(&id, json!({"item": item.0, "path": picked})).map_err(|e| e.to_string())
+ }))
}
"file.projectManager" => Some(enabled(app, id).map(|_| {
let seqs = app.session.state.active_sequence.map(|s| vec![s.0]).unwrap_or_default();
@@ -292,26 +289,13 @@ fn link_media(app: &mut FilmcraftApp, ctx: &egui::Context) {
action = Some("cancel");
}
let (item, ..) = rows[d.row].clone();
- let relink = |app: &mut FilmcraftApp, d: &mut LinkMediaDraft, path: String| {
- let mut p = match_params(d);
- p["item"] = json!(item);
- p["path"] = json!(path);
- match app.session.execute("media.relink", p) {
- Ok(v) => {
- d.message.clear();
- d.candidates.clear();
- d.candidate = None;
- app.ui.status = tlf!("Linked {n} clip(s)", n = v["relinked"].as_array().map_or(0, Vec::len));
- }
- Err(e) => d.message = e.to_string(),
- }
- };
+ let relink = |app: &mut FilmcraftApp, d: &mut LinkMediaDraft, path: String| relink_to(app, d, &json!(item), path);
match action {
- Some("browse") => {
- if let Some(f) = app.hooks.pick_folder.as_mut().and_then(|f| f()) {
+ Some("browse") => app.pick_ui(FileDialog::Folder { at: None }, |app, paths| {
+ if let (Some(f), Some(d)) = (paths.into_iter().next(), app.ui.link_media.as_mut()) {
d.folder = f;
}
- }
+ }),
Some("search") => {
let mut p = match_params(&d);
p["folder"] = json!(d.folder);
@@ -343,16 +327,12 @@ fn link_media(app: &mut FilmcraftApp, ctx: &egui::Context) {
let mut params = match_params(&d);
params["item"] = json!(item);
let hint = RelinkHint { command: "media.relink".into(), params };
- let picked = if let Some(picker) = app.hooks.pick_file_for_relink.as_mut() {
- picker(&exts, Some(hint))
- } else if let Some(picker) = app.hooks.pick_files.as_mut() {
- picker(&exts).into_iter().next()
- } else {
- None
- };
- if let Some(path) = picked {
- relink(app, &mut d, path);
- }
+ let item = json!(item);
+ app.pick_ui(FileDialog::Relink { exts: exts.iter().map(|e| e.to_string()).collect(), hint }, move |app, paths| {
+ let (Some(path), Some(mut d)) = (paths.into_iter().next(), app.ui.link_media.clone()) else { return };
+ relink_to(app, &mut d, &item, path);
+ app.ui.link_media = Some(d);
+ });
}
Some("link") => {
if let Some(path) = d.candidate.and_then(|c| d.candidates.get(c)).map(|c| c.0.clone()) {
@@ -462,8 +442,12 @@ fn create_proxies(app: &mut FilmcraftApp, ctx: &egui::Context) {
for (id, r, l) in elems {
app.auto.add(&id, r, &l);
}
- if browse && let Some(f) = app.hooks.pick_folder.as_mut().and_then(|f| f()) {
- d.destination = f;
+ if browse {
+ app.pick_ui(FileDialog::Folder { at: None }, |app, paths| {
+ if let (Some(f), Some(d)) = (paths.into_iter().next(), app.ui.create_proxies.as_mut()) {
+ d.destination = f;
+ }
+ });
}
if ok {
let p = json!({"items": d.items, "preset": d.preset, "destination": if d.destination.is_empty() { Value::Null } else { json!(d.destination) }});
@@ -591,8 +575,12 @@ fn project_manager(app: &mut FilmcraftApp, ctx: &egui::Context) {
for (id, r, l) in elems {
app.auto.add(&id, r, &l);
}
- if browse && let Some(f) = app.hooks.pick_folder.as_mut().and_then(|f| f()) {
- d.destination = f;
+ if browse {
+ app.pick_ui(FileDialog::Folder { at: None }, |app, paths| {
+ if let (Some(f), Some(d)) = (paths.into_iter().next(), app.ui.project_manager.as_mut()) {
+ d.destination = f;
+ }
+ });
}
// settings changed: the estimate is stale
if (d.mode != before.mode
@@ -625,3 +613,19 @@ fn project_manager(app: &mut FilmcraftApp, ctx: &egui::Context) {
}
app.ui.project_manager = (keep && !ctx.input(|i| i.key_pressed(egui::Key::Escape))).then_some(d);
}
+
+/// Link Media: relink `item` to `path` with the dialog's matching options; the result goes into `d`.
+fn relink_to(app: &mut FilmcraftApp, d: &mut LinkMediaDraft, item: &Value, path: String) {
+ let mut p = match_params(d);
+ p["item"] = item.clone();
+ p["path"] = json!(path);
+ match app.session.execute("media.relink", p) {
+ Ok(v) => {
+ d.message.clear();
+ d.candidates.clear();
+ d.candidate = None;
+ app.ui.status = tlf!("Linked {n} clip(s)", n = v["relinked"].as_array().map_or(0, Vec::len));
+ }
+ Err(e) => d.message = e.to_string(),
+ }
+}
diff --git a/crates/ui-egui/src/panels/menu_dialogs.rs b/crates/ui-egui/src/panels/menu_dialogs.rs
index e3431398a..5f4dfe0d7 100644
--- a/crates/ui-egui/src/panels/menu_dialogs.rs
+++ b/crates/ui-egui/src/panels/menu_dialogs.rs
@@ -23,6 +23,7 @@ use serde_json::{Value, json};
use crate::FilmcraftApp;
use crate::dock::PanelKind;
+use crate::native_dialogs::FileDialog;
use crate::state::ClipDialogDraft;
/// Frontend state of the M3.11 menu items (`UiState::extras`).
@@ -213,26 +214,30 @@ pub fn route(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: &Val
} else {
(tl!("FilmCraft Project"), "fcproj", tlf!("{name} Selection.fcproj", name = app.session.project.name))
};
- let Some(path) = app.hooks.pick_save_as.as_mut().and_then(|f| f(filter, &[ext], &name)) else {
- return Some(Ok(Value::Null));
- };
let mut p = params.clone();
if !p.is_object() {
p = json!({});
}
- p["path"] = json!(path);
- return Some(app.session.execute(id, p).map_err(|e| e.to_string()));
+ let id = id.to_string();
+ return Some(app.pick(FileDialog::save_as(filter, &[ext], &name), move |app, paths| {
+ let Some(path) = paths.into_iter().next() else { return Ok(Value::Null) };
+ p["path"] = json!(path);
+ app.session.execute(&id, p).map_err(|e| e.to_string())
+ }));
}
"file.mediaPropertiesFile" if params.get("path").is_none() => {
let exts: Vec<&str> =
filmcraft_media::VIDEO_EXTENSIONS.iter().chain(filmcraft_media::AUDIO_EXTENSIONS).chain(filmcraft_media::STILL_EXTENSIONS).copied().collect();
- let Some(path) = app.hooks.pick_open_file.as_mut().and_then(|f| f(tl!("Media"), &exts)) else { return Some(Ok(Value::Null)) };
- let r = app.session.execute(id, json!({"path": path})).map_err(|e| e.to_string());
- if let Ok(v) = &r {
- app.ui.extras.dialog =
- Some(ClipDialogDraft { command: "file.mediaProperties".into(), params: json!({}), info: json!([v]), error: String::new() });
- }
- return Some(r);
+ let id = id.to_string();
+ return Some(app.pick(FileDialog::open_file(tl!("Media"), &exts), move |app, paths| {
+ let Some(path) = paths.into_iter().next() else { return Ok(Value::Null) };
+ let r = app.session.execute(&id, json!({"path": path})).map_err(|e| e.to_string());
+ if let Ok(v) = &r {
+ app.ui.extras.dialog =
+ Some(ClipDialogDraft { command: "file.mediaProperties".into(), params: json!({}), info: json!([v]), error: String::new() });
+ }
+ r
+ }));
}
_ => {}
}
@@ -822,10 +827,16 @@ pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {
for (id, r, l) in elems {
app.auto.add(&id, r, &l);
}
- if let Some(k) = browse
- && let Some(dir) = app.hooks.pick_folder.as_mut().and_then(|f| f())
- {
- d.params[k.as_str()] = json!(dir);
+ if let Some(k) = browse {
+ // into the dialog's parameters, if the same dialog is still open when the folder comes back
+ let command = d.command.clone();
+ app.pick_ui(FileDialog::Folder { at: None }, move |app, paths| {
+ if let (Some(dir), Some(d)) = (paths.into_iter().next(), app.ui.extras.dialog.as_mut())
+ && d.command == command
+ {
+ d.params[k.as_str()] = json!(dir);
+ }
+ });
}
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
action = Some("cancel");
diff --git a/crates/ui-egui/src/panels/presets.rs b/crates/ui-egui/src/panels/presets.rs
index 61e6bb18f..b6639bda3 100644
--- a/crates/ui-egui/src/panels/presets.rs
+++ b/crates/ui-egui/src/panels/presets.rs
@@ -10,6 +10,7 @@ use serde_json::json;
use crate::FilmcraftApp;
use crate::icons::{self, Icon};
+use crate::native_dialogs::FileDialog;
use crate::state::SavePresetDraft;
use crate::theme::Tokens;
@@ -66,12 +67,23 @@ pub fn run(app: &mut FilmcraftApp, cmd: &str, name: &str) {
"presets.apply" => app.session.execute(cmd, json!({"preset": name})),
"presets.delete" => app.session.execute(cmd, json!({"name": name})),
"presets.export" => {
- let Some(path) = app.hooks.pick_save_as.as_mut().and_then(|f| f(tl!("Effect presets"), &["json"], &format!("{name}.json"))) else { return };
- app.session.execute(cmd, json!({"path": path, "names": [name]}))
+ let name = name.to_string();
+ app.pick_ui(FileDialog::save_as(tl!("Effect presets"), &["json"], &format!("{name}.json")), move |app, paths| {
+ let Some(path) = paths.into_iter().next() else { return };
+ if let Err(e) = app.session.execute("presets.export", json!({"path": path, "names": [name]})) {
+ app.ui.status = e.to_string();
+ }
+ });
+ return;
}
"presets.import" => {
- let Some(path) = app.hooks.pick_open_file.as_mut().and_then(|f| f(tl!("Effect presets"), &["json"])) else { return };
- app.session.execute(cmd, json!({"path": path}))
+ app.pick_ui(FileDialog::open_file(tl!("Effect presets"), &["json"]), |app, paths| {
+ let Some(path) = paths.into_iter().next() else { return };
+ if let Err(e) = app.session.execute("presets.import", json!({"path": path})) {
+ app.ui.status = e.to_string();
+ }
+ });
+ return;
}
_ => return,
};
diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs
index 241c59755..6beb00b10 100644
--- a/crates/ui-egui/src/panels/settings.rs
+++ b/crates/ui-egui/src/panels/settings.rs
@@ -17,6 +17,7 @@ use filmcraft_project::Label;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
+use crate::native_dialogs::FileDialog;
use crate::theme::Tokens;
use crate::{AudioDevices, Dialog, FilmcraftApp};
@@ -323,10 +324,13 @@ fn draw_field(app: &mut FilmcraftApp, ui: &mut Ui, d: &mut SettingsDraft, f: &Fi
if matches!(f.kind, Kind::Path) {
let b = ui.button(tl!("Browse…"));
app.auto.add(&format!("settings.{}.browse", f.key), b.rect, "Browse…");
- if b.clicked()
- && let Some(dir) = app.hooks.pick_folder.as_mut().and_then(|p| p())
- {
- put(&mut d.values, f.key, json!(dir));
+ if b.clicked() {
+ let key = f.key;
+ app.pick_ui(FileDialog::Folder { at: None }, move |app, paths| {
+ if let (Some(dir), Some(d)) = (paths.into_iter().next(), app.ui.settings.as_mut()) {
+ put(&mut d.values, key, json!(dir));
+ }
+ });
}
}
}
diff --git a/crates/ui-egui/src/panels/shortcuts_dialog.rs b/crates/ui-egui/src/panels/shortcuts_dialog.rs
index 0e6845a88..f5464f5b6 100644
--- a/crates/ui-egui/src/panels/shortcuts_dialog.rs
+++ b/crates/ui-egui/src/panels/shortcuts_dialog.rs
@@ -19,6 +19,7 @@ use serde::Serialize;
use serde_json::{Value, json};
use crate::FilmcraftApp;
+use crate::native_dialogs::FileDialog;
use crate::theme::Tokens;
/// Key colours (our own palette): application-wide, panel-specific, unassigned, held modifier.
@@ -234,26 +235,24 @@ fn header(app: &mut FilmcraftApp, ui: &mut egui::Ui, t: &Tokens) {
app.shortcut_editor.message = tlf!("Deleted preset “{active}”", active);
}
if small_button(app, ui, "shortcuts.export", tl!("Export…"), true) {
- let picked = app.hooks.pick_save_as.as_mut().and_then(|f| f(tl!("Keyboard Shortcuts"), &["json"], &format!("{active}.json")));
- match picked {
+ app.pick_ui(FileDialog::save_as(tl!("Keyboard Shortcuts"), &["json"], &format!("{active}.json")), |app, paths| match paths.into_iter().next() {
Some(path) => {
if exec(app, "shortcuts.export", json!({"path": path})).is_some() {
app.shortcut_editor.message = tlf!("Exported to {path}", path);
}
}
None => app.shortcut_editor.message = tl!("Export: no file chosen (agents: shortcuts.export {path})").into(),
- }
+ });
}
if small_button(app, ui, "shortcuts.import", tl!("Import…"), true) {
- let picked = app.hooks.pick_open_file.as_mut().and_then(|f| f(tl!("Keyboard Shortcuts"), &["json"]));
- match picked {
+ app.pick_ui(FileDialog::open_file(tl!("Keyboard Shortcuts"), &["json"]), |app, paths| match paths.into_iter().next() {
Some(path) => {
if let Some(r) = exec(app, "shortcuts.import", json!({"path": path})) {
app.shortcut_editor.message = tlf!("Imported “{name}”", name = r["name"].as_str().unwrap_or(""));
}
}
None => app.shortcut_editor.message = tl!("Import: no file chosen (agents: shortcuts.import {path})").into(),
- }
+ });
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(RichText::new(if cfg!(target_os = "macos") { tl!("Keyboard: US (macOS)") } else { tl!("Keyboard: US") }).size(12.0).color(t.text_dim));
diff --git a/crates/ui-egui/tests/native_dialogs_ui.rs b/crates/ui-egui/tests/native_dialogs_ui.rs
new file mode 100644
index 000000000..9bbad64a8
--- /dev/null
+++ b/crates/ui-egui/tests/native_dialogs_ui.rs
@@ -0,0 +1,221 @@
+//! File dialogs that don't stop the frame loop (#260), headless with a stand-in host runner
+//! (`HostHooks::run_dialog`) the test answers by hand: while a dialog is open the app keeps
+//! answering requests and drawing, and the chosen path is used when the answer arrives (a menu
+//! command, a panel's field), cancelled or lost dialogs do nothing, one dialog is open at a time,
+//! and a path for a dialog the user has closed meanwhile goes nowhere. Also: with the synchronous
+//! pickers (no runner) a panel's Browse… still fills its field.
+
+use std::path::PathBuf;
+use std::sync::mpsc::{Receiver, Sender, channel};
+use std::sync::{Arc, Mutex};
+
+use egui_kittest::Harness;
+use filmcraft_engine::Session;
+use filmcraft_ui_egui::FilmcraftApp;
+use filmcraft_ui_egui::control::ControlRequest;
+use filmcraft_ui_egui::native_dialogs::FileDialog;
+use serde_json::{Value, json};
+
+/// Dialogs the app asked for, with the sender that answers each.
+type Asked = Arc<Mutex<Vec<(FileDialog, Sender<Vec<String>>)>>>;
+
+struct Driver {
+ harness: Harness<'static, FilmcraftApp>,
+ tx: Sender<ControlRequest>,
+ asked: Asked,
+}
+
+impl Driver {
+ /// The demo project; `runner`: dialogs go to the stand-in host runner (else synchronous hooks).
+ fn new(runner: bool) -> Self {
+ let mut session = Session::default();
+ session.execute("file.openDemoProject", json!({})).expect("demo project");
+ let (tx, rx) = channel();
+ let mut app = FilmcraftApp::new(session).with_control(rx);
+ let asked: Asked = Arc::default();
+ if runner {
+ let a = asked.clone();
+ app.hooks.run_dialog = Some(Box::new(move |dialog: FileDialog| -> Receiver<Vec<String>> {
+ let (tx, rx) = channel();
+ a.lock().unwrap().push((dialog, tx));
+ rx
+ }));
+ }
+ let harness = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000).build_eframe(move |_cc| app);
+ let mut d = Driver { harness, tx, asked };
+ d.frames(4);
+ d
+ }
+
+ fn frames(&mut self, n: usize) {
+ for _ in 0..n {
+ let ctx = self.harness.ctx.clone();
+ let mut raw = std::mem::take(self.harness.input_mut());
+ eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw);
+ *self.harness.input_mut() = raw;
+ self.harness.step();
+ }
+ }
+
+ fn call(&mut self, method: &str, params: Value) -> Value {
+ let (req, reply) = ControlRequest::new(method, params.clone());
+ self.tx.send(req).unwrap();
+ for _ in 0..600 {
+ self.frames(1);
+ if let Ok(v) = reply.try_recv() {
+ return v;
+ }
+ }
+ panic!("no reply to {method} {params}");
+ }
+
+ fn ok(&mut self, method: &str, params: Value) -> Value {
+ let r = self.call(method, params.clone());
+ assert_eq!(r["ok"], true, "{method} {params}: {r}");
+ r["result"].clone()
+ }
+
+ fn click(&mut self, id: &str) {
+ self.ok("ui.click", json!({"id": id}));
+ self.frames(3);
+ }
+
+ fn app(&mut self) -> &mut FilmcraftApp {
+ self.harness.state_mut()
+ }
+
+ /// The one dialog asked for so far (taken), with its answering sender.
+ fn asked(&mut self) -> (FileDialog, Sender<Vec<String>>) {
+ let mut a = self.asked.lock().unwrap();
+ assert_eq!(a.len(), 1, "one dialog asked for: {:?}", a.iter().map(|x| &x.0).collect::<Vec<_>>());
+ a.pop().unwrap()
+ }
+
+ fn items(&mut self) -> usize {
+ self.app().session.project.items.len()
+ }
+}
+
+/// A one-second 8 kHz mono WAV in Cargo's temporary folder for integration tests.
+fn wav() -> PathBuf {
+ let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("native-dialogs");
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("tone.wav");
+ let (rate, n) = (8000u32, 8000u32);
+ let mut b = Vec::new();
+ b.extend_from_slice(b"RIFF");
+ b.extend_from_slice(&(36 + n * 2).to_le_bytes());
+ b.extend_from_slice(b"WAVEfmt ");
+ b.extend_from_slice(&16u32.to_le_bytes());
+ b.extend_from_slice(&1u16.to_le_bytes());
+ b.extend_from_slice(&1u16.to_le_bytes());
+ b.extend_from_slice(&rate.to_le_bytes());
+ b.extend_from_slice(&(rate * 2).to_le_bytes());
+ b.extend_from_slice(&2u16.to_le_bytes());
+ b.extend_from_slice(&16u16.to_le_bytes());
+ b.extend_from_slice(b"data");
+ b.extend_from_slice(&(n * 2).to_le_bytes());
+ for i in 0..n {
+ b.extend_from_slice(&(((i as f32 * 0.2).sin() * 8000.0) as i16).to_le_bytes());
+ }
+ std::fs::write(&path, b).unwrap();
+ path
+}
+
+#[test]
+fn the_app_keeps_running_while_the_import_dialog_is_open_and_imports_when_it_answers() {
+ let mut d = Driver::new(true);
+ let before = d.items();
+ // File ▸ Import answers at once: the dialog is open, nothing is imported yet
+ assert_eq!(d.ok("ui.menu.invoke", json!({"id": "file.import"})), json!({"dialog": "open"}));
+ assert!(d.app().native_dialog_open());
+ let (dialog, answer) = d.asked();
+ assert!(matches!(&dialog, FileDialog::OpenFiles { exts } if exts.iter().any(|e| e == "wav")), "{dialog:?}");
+ // the frame loop runs and requests are answered while the dialog is open
+ for _ in 0..5 {
+ d.ok("ui.inspect", json!({}));
+ }
+ d.frames(20);
+ assert_eq!(d.items(), before);
+ // the user chooses a file: it is imported on the next frame
+ answer.send(vec![wav().to_string_lossy().into_owned()]).unwrap();
+ d.frames(2);
+ assert!(!d.app().native_dialog_open());
+ assert_eq!(d.items(), before + 1);
+ assert!(d.app().session.project.items.values().any(|i| i.name == "tone.wav"));
+}
+
+#[test]
+fn cancelled_or_lost_dialogs_do_nothing_and_one_dialog_is_open_at_a_time() {
+ let mut d = Driver::new(true);
+ let before = d.items();
+ d.ok("ui.menu.invoke", json!({"id": "file.import"}));
+ // a second dialog while one is open is refused
+ let r = d.call("ui.menu.invoke", json!({"id": "file.open"}));
+ assert_eq!(r["ok"], false, "{r}");
+ assert!(r.to_string().contains("already open"), "{r}");
+ let (_, answer) = d.asked();
+ // cancelled: no path
+ answer.send(vec![]).unwrap();
+ d.frames(2);
+ assert!(!d.app().native_dialog_open());
+ assert_eq!(d.items(), before);
+ // the host's dialog went away without an answer (its thread failed): as if cancelled
+ d.ok("ui.menu.invoke", json!({"id": "file.import"}));
+ let (_, answer) = d.asked();
+ drop(answer);
+ d.frames(2);
+ assert!(!d.app().native_dialog_open());
+ assert_eq!(d.items(), before);
+ // and the next dialog opens normally
+ assert_eq!(d.ok("ui.menu.invoke", json!({"id": "file.open"})), json!({"dialog": "open"}));
+ assert!(matches!(d.asked().0, FileDialog::OpenProject));
+}
+
+#[test]
+fn a_panel_folder_arrives_in_its_open_dialog_and_nowhere_once_it_is_closed() {
+ let mut d = Driver::new(true);
+ // Settings ▸ Media Cache ▸ Location ▸ Browse…
+ d.ok("ui.menu.invoke", json!({"id": "app.settings.mediaCache"}));
+ d.frames(3);
+ d.click("settings.mediaCache.location.browse");
+ let (dialog, answer) = d.asked();
+ assert!(matches!(dialog, FileDialog::Folder { .. }), "{dialog:?}");
+ d.frames(10);
+ answer.send(vec!["/tmp/filmcraft-cache-test".into()]).unwrap();
+ d.frames(3);
+ let loc = d.app().ui.settings.as_ref().map(|s| s.values.pointer("/mediaCache/location").cloned());
+ assert_eq!(loc, Some(Some(json!("/tmp/filmcraft-cache-test"))));
+ // Browse… again, then Cancel the Settings dialog before the folder comes back: nothing to write into
+ d.click("settings.mediaCache.location.browse");
+ let (_, answer) = d.asked();
+ d.click("settings.cancel");
+ assert!(d.app().ui.settings.is_none());
+ answer.send(vec!["/tmp/elsewhere".into()]).unwrap();
+ d.frames(3);
+ assert!(d.app().ui.settings.is_none());
+ assert!(!d.app().native_dialog_open());
+ assert_ne!(d.app().session.prefs.to_value().pointer("/mediaCache/location"), Some(&json!("/tmp/elsewhere")));
+}
+
+#[test]
+fn export_location_browse_works_with_the_runner_and_with_synchronous_pickers() {
+ // runner: the folder arrives later
+ let mut d = Driver::new(true);
+ d.ok("ui.set", json!({"mode": "export"}));
+ d.frames(3);
+ d.click("export.location.browse");
+ let (_, answer) = d.asked();
+ answer.send(vec!["/tmp/exports-a".into()]).unwrap();
+ d.frames(2);
+ assert_eq!(d.app().ui.export.location, "/tmp/exports-a");
+
+ // synchronous picker (no runner, as on macOS / Windows / other hosts): still filled in
+ let mut d = Driver::new(false);
+ d.app().hooks.pick_folder = Some(Box::new(|| Some("/tmp/exports-b".into())));
+ d.ok("ui.set", json!({"mode": "export"}));
+ d.frames(3);
+ d.click("export.location.browse");
+ assert_eq!(d.app().ui.export.location, "/tmp/exports-b");
+ assert!(!d.app().native_dialog_open());
+}