PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Linux: say so when no file dialog can open (#3354); read ldconfig on non-English systems (#3397)
DomiLuebbenb3993e89b351
diff --git a/apps/photocraft/src/file_dialog_probe.rs b/apps/photocraft/src/file_dialog_probe.rsnew file mode 100644index 000000000..9ee14c0af--- /dev/null+++ b/apps/photocraft/src/file_dialog_probe.rs@@ -0,0 +1,129 @@+//! Why a File › Open / Save dialog may never appear on Linux (#3354).+//!+//! `rfd` talks to the XDG file-chooser portal through `libdbus-1`, which it loads at runtime, and+//! falls back to `zenity`. When neither works (a minimal window-manager session without a portal+//! backend) it logs the failure and answers "nothing picked", which the app took for Cancel: the+//! menu item did nothing and said nothing. [`start`] looks for the pieces once, in the background,+//! and [`known_problem`] returns what to install when a dialog came back empty and none of them+//! is there.+//!+//! The probe only ever explains an empty answer; it never stops a dialog from opening. Anything+//! it can't tell counts as present, so a working system never sees the message.++use std::sync::OnceLock;++/// What the probe found. `None` means it couldn't tell, which counts as present.+// Only Linux probes; the types and helpers stay testable on every platform.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Findings {+ /// `libdbus-1.so.3` is in the linker cache (`rfd` loads it for the portal).+ pub libdbus: Option<bool>,+ /// The session bus has the portal's `FileChooser` interface (a portal and a backend for it).+ pub file_chooser_portal: Option<bool>,+ /// `zenity` is on `PATH` (`rfd`'s fallback).+ pub zenity: bool,+}++/// The message for `findings`, or `None` when some file dialog should work.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+pub fn problem(findings: Findings) -> Option<String> {+ let portal = findings.libdbus != Some(false) && findings.file_chooser_portal != Some(false);+ if portal || findings.zenity {+ return None;+ }+ let cause = if findings.libdbus == Some(false) { "libdbus is missing" } else { "no desktop portal offers a file chooser" };+ Some(format!(+ "No file dialog can open: {cause}. Install xdg-desktop-portal with a backend (xdg-desktop-portal-gtk, -kde or -gnome) and libdbus, or zenity. Meanwhile, drop a file onto the window or paste a copied image."+ ))+}++static RESULT: OnceLock<Option<String>> = OnceLock::new();++/// The problem found by [`start`], once it has finished.+pub fn known_problem() -> Option<String> {+ RESULT.get().cloned().flatten()+}++/// Whether `program` is an executable file in one of the `path` directories.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn on_path(program: &str, path: &std::ffi::OsStr) -> bool {+ std::env::split_paths(path).any(|dir| dir.join(program).is_file())+}++/// Look for the file dialog backends on a helper thread (the portal call can take a moment).+#[cfg(target_os = "linux")]+pub fn start() {+ let spawned = std::thread::Builder::new().name("file dialog probe".into()).spawn(|| {+ let findings = Findings {+ libdbus: crate::linux_libs::cached("libdbus-1.so.3"),+ file_chooser_portal: file_chooser_portal(),+ zenity: std::env::var_os("PATH").is_some_and(|path| on_path("zenity", &path)),+ };+ log::info!("file dialog backends: {findings:?}");+ let _ = RESULT.set(problem(findings));+ });+ if let Err(e) = spawned {+ log::warn!("couldn't start the file dialog probe: {e}");+ }+}++/// Whether the portal's `FileChooser` interface is on the session bus: `Some(false)` only when the+/// bus or the interface is definitely absent, `None` for anything inconclusive (a slow reply).+#[cfg(target_os = "linux")]+fn file_chooser_portal() -> Option<bool> {+ let Ok(conn) = zbus::blocking::connection::Builder::session().and_then(|b| b.method_timeout(std::time::Duration::from_secs(5)).build()) else {+ return Some(false);+ };+ let proxy = zbus::blocking::proxy::Builder::<zbus::blocking::Proxy<'_>>::new(&conn)+ .destination("org.freedesktop.portal.Desktop")+ .and_then(|b| b.path("/org/freedesktop/portal/desktop"))+ .and_then(|b| b.interface("org.freedesktop.portal.FileChooser"))+ .and_then(|b| b.cache_properties(zbus::proxy::CacheProperties::No).build())+ .ok()?;+ match proxy.get_property::<u32>("version") {+ Ok(_) => Some(true),+ Err(zbus::Error::MethodError(name, _, _)) => {+ let name = name.as_str();+ let absent = ["ServiceUnknown", "UnknownObject", "UnknownInterface", "UnknownProperty"].iter().any(|n| name.ends_with(n));+ absent.then_some(false)+ }+ Err(_) => None,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn found(libdbus: Option<bool>, file_chooser_portal: Option<bool>, zenity: bool) -> Findings {+ Findings { libdbus, file_chooser_portal, zenity }+ }++ #[test]+ fn a_working_backend_is_not_reported() {+ assert_eq!(problem(found(Some(true), Some(true), false)), None, "portal");+ assert_eq!(problem(found(Some(false), Some(false), true)), None, "zenity alone");+ assert_eq!(problem(found(None, None, false)), None, "unknown counts as present");+ assert_eq!(problem(found(Some(true), None, false)), None, "slow portal reply");+ }++ #[test]+ fn nothing_to_show_a_dialog_with_is_explained() {+ let no_portal = problem(found(Some(true), Some(false), false)).unwrap();+ assert!(no_portal.contains("no desktop portal offers a file chooser") && no_portal.contains("xdg-desktop-portal"), "{no_portal}");+ let no_dbus = problem(found(Some(false), Some(true), false)).unwrap();+ assert!(no_dbus.contains("libdbus is missing"), "{no_dbus}");+ }++ #[test]+ fn programs_are_found_on_the_given_path() {+ let dir = std::env::temp_dir().join(format!("photocraft-probe-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("zenity"), b"").unwrap();+ let path = std::env::join_paths([std::path::Path::new("/nonexistent"), dir.as_path()]).unwrap();+ assert!(on_path("zenity", &path));+ assert!(!on_path("kdialog", &path));+ std::fs::remove_dir_all(&dir).unwrap();+ }+}diff --git a/apps/photocraft/src/linux_libs.rs b/apps/photocraft/src/linux_libs.rsindex 3cf1fdd12..b1682144d 100644--- a/apps/photocraft/src/linux_libs.rs+++ b/apps/photocraft/src/linux_libs.rs@@ -111,9 +111,10 @@ pub fn ldconfig_has(output: &str, soname: &str, arch_tag: Option<&str>) -> bool})}-/// A real `ldconfig -p` listing starts with "N libs found in cache".+/// A real `ldconfig -p` listing starts with "N libs found in cache" (translated on a system whose+/// locale `LC_ALL=C` doesn't reach): a count, then the cache's name.fn ldconfig_output_is_valid(output: &str) -> bool {- output.lines().next().is_some_and(|l| l.contains("libs found in cache"))+ output.lines().next().is_some_and(|l| l.split_whitespace().next().is_some_and(|n| n.parse::<u32>().is_ok()))}/// Where we look for libraries, and what we found there.@@ -245,7 +246,9 @@ fn search_dirs(ld_library_path: Option<&str>) -> Vec<PathBuf> {/// `ldconfig -p`, from the usual locations (`/sbin` isn't on a normal user's PATH on Debian).fn read_ldconfig() -> Option<String> {for cmd in ["/sbin/ldconfig", "/usr/sbin/ldconfig", "ldconfig"] {- if let Ok(out) = std::process::Command::new(cmd).arg("-p").output()+ // The listing is parsed, so it must be the untranslated one: a German system prints+ // "5522 Bibliotheken im Cache", which `ldconfig_output_is_valid` took for no cache at all.+ if let Ok(out) = std::process::Command::new(cmd).arg("-p").env("LC_ALL", "C").output()&& out.status.success(){let text = String::from_utf8_lossy(&out.stdout).into_owned();@@ -262,6 +265,12 @@ fn system_probe() -> Probe {Probe { ldconfig: read_ldconfig(), dirs: search_dirs(std::env::var("LD_LIBRARY_PATH").ok().as_deref()) }}+/// Whether the linker cache lists `soname`; `None` when the cache can't be read, which proves+/// nothing (musl, NixOS, some containers).+pub fn cached(soname: &str) -> Option<bool> {+ read_ldconfig().map(|text| ldconfig_has(&text, soname, ldconfig_arch_tag()))+}+/// Are all the libraries `session` needs found on this system? (For choosing a display server:/// libraries the check can't find count as missing.)pub fn available(session: DisplaySession) -> bool {@@ -325,6 +334,10 @@ mod tests {fn ldconfig_parsing_matches_name_and_architecture() {assert!(ldconfig_output_is_valid(CACHE));assert!(!ldconfig_output_is_valid("ldconfig: command not found"));+ // A translated listing is still a listing (it used to be rejected, so the check was+ // silently skipped on non-English systems).+ assert!(ldconfig_output_is_valid("5522 Bibliotheken im Cache »/etc/ld.so.cache« gefunden\n\tlibz.so.1 (libc6,x86-64) => /usr/lib/libz.so.1\n"));+ assert!(!ldconfig_output_is_valid("Error: kein Cache\n"));assert!(ldconfig_has(CACHE, "libxkbcommon.so.0", Some("x86-64")));// Only the 32-bit build is installed: doesn't count for a 64-bit app.assert!(!ldconfig_has(CACHE, "libxkbcommon-x11.so.0", Some("x86-64")));diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rsindex f9faee37d..b7d5253d5 100644--- a/apps/photocraft/src/main.rs+++ b/apps/photocraft/src/main.rs@@ -29,6 +29,7 @@ mod caps_lock;mod control_server;mod crash_guard;mod cursor;+mod file_dialog_probe;mod gpu_startup;#[cfg(target_os = "macos")]mod mac_menu;@@ -357,6 +358,7 @@ fn main() -> eframe::Result {#[cfg(target_os = "linux")]{services.is_wayland = display == Some(tablet::DisplayKind::Wayland);+ file_dialog_probe::start();if services.is_wayland {let var = |name| std::env::var(name).ok();services.xwayland_command =diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rsindex 739fb2363..1d25ac2a0 100644--- a/apps/photocraft/src/services.rs+++ b/apps/photocraft/src/services.rs@@ -130,7 +130,11 @@ fn show_file_dialog(request: FileDialogRequest, parent: Option<&eframe::Frame>,}};// Without the thread the reply is dropped unanswered, which the app takes as Cancel.- if let Err(e) = std::thread::Builder::new().name("file dialog".into()).spawn(move || reply.send(block_on(answer))) {+ if let Err(e) = std::thread::Builder::new().name("file dialog".into()).spawn(move || {+ // An empty answer from a system with no dialog backend isn't a Cancel (#3354).+ let answer = block_on(answer).or_else(|| crate::file_dialog_probe::known_problem().map(FileDialogAnswer::Unavailable));+ reply.send(answer)+ }) {log::error!("couldn't wait for the file dialog: {e}");}}diff --git a/crates/ui-egui/src/file_dialog.rs b/crates/ui-egui/src/file_dialog.rsindex 1b794b57e..a1f6e5240 100644--- a/crates/ui-egui/src/file_dialog.rs+++ b/crates/ui-egui/src/file_dialog.rs@@ -42,6 +42,9 @@ pub enum FileDialogAnswer {ContentsMany(Vec<(String, Vec<u8>)>),/// The path to save to (desktop), or the download's name (web).SaveTo(String),+ /// No dialog could be shown (on Linux: no desktop portal and no zenity, #3354); the message+ /// says what to install. Reported as an error rather than taken for Cancel.+ Unavailable(String),}/// Hands a dialog's answer to the app and wakes it, from any thread. Dropping it unanswered@@ -102,7 +105,11 @@ impl PhotocraftApp {FileDialogRequest::Open { .. } => "open",FileDialogRequest::Save { .. } => "save",};- let then: Then = Box::new(move |app, answer| answer.map_or_else(|| Err(CANCELLED.into()), |a| then(app, a)));+ let then: Then = Box::new(move |app, answer| match answer {+ None => Err(CANCELLED.into()),+ Some(FileDialogAnswer::Unavailable(why)) => Err(why),+ Some(a) => then(app, a),+ });self.file_dialog = Some(Pending { request: Some(request), answer: None, then });Ok(json!({ "fileDialog": kind }))}@@ -186,7 +193,7 @@ impl PhotocraftApp {}FileDialogAnswer::Contents(name, bytes) => app.open_contents(vec![(name, bytes)]),FileDialogAnswer::ContentsMany(files) => app.open_contents(files),- FileDialogAnswer::SaveTo(_) => return Err(UNEXPECTED.into()),+ FileDialogAnswer::SaveTo(_) | FileDialogAnswer::Unavailable(_) => return Err(UNEXPECTED.into()),}Ok(Value::Null)})@@ -283,7 +290,7 @@ fn read_picked(answer: FileDialogAnswer) -> Result<(String, Vec<u8>), String> {let bytes = photocraft_format::read_file(std::path::Path::new(&path)).map_err(|e| format!("{}: {e}", display_name(&path)))?;Ok((path, bytes))}- FileDialogAnswer::SaveTo(_) => Err(UNEXPECTED.into()),+ FileDialogAnswer::SaveTo(_) | FileDialogAnswer::Unavailable(_) => Err(UNEXPECTED.into()),}}diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rsindex dc4db4c51..d166d89a8 100644--- a/crates/ui-egui/src/file_dialog/tests.rs+++ b/crates/ui-egui/src/file_dialog/tests.rs@@ -586,3 +586,25 @@ fn convert_to_linked_asks_where_to_write_the_contents() {assert_eq!(smart_source(&app, id), photocraft_doc::SmartSource::Linked { path: path.clone() });}}++/// #3354: a system with no dialog backend answers `Unavailable`; the message reaches the status+/// bar as an error, where a cancelled dialog stays silent.+#[test]+fn an_unavailable_dialog_is_reported_and_a_cancelled_one_is_not() {+ let ctx = egui::Context::default();+ let (mut app, open, _) = app();+ menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap();+ app.poll_file_dialog(&ctx, None);+ answer(&open, None);+ app.poll_file_dialog(&ctx, None);+ assert!(!app.ui.status_error, "Cancel is the user's choice");+ assert!(!app.file_dialog_open());++ menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap();+ app.poll_file_dialog(&ctx, None);+ answer(&open, Some(FileDialogAnswer::Unavailable("No file dialog can open".into())));+ app.poll_file_dialog(&ctx, None);+ assert!(app.ui.status_error);+ assert_eq!(app.ui.status, "No file dialog can open");+ assert!(!app.file_dialog_open(), "the pending dialog is over");+}