mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-03 06:31:42 +01:00
* feat(linux): say so when no file dialog can open (#3354) File › Open / Save / Export did nothing on a minimal Wayland session (labwc, Void) and said nothing: rfd loads libdbus-1 for the XDG file chooser portal and falls back to zenity, and when neither works it only logs and answers "nothing picked", which the app took for Cancel. A background probe now looks once for the pieces (libdbus in the linker cache, the portal's FileChooser interface on the session bus, zenity on PATH). When a dialog comes back empty and none of them is there, the shell answers with the new FileDialogAnswer::Unavailable and the status bar tells the user what to install. The probe only explains an empty answer; it never blocks a dialog, and anything it can't tell counts as present. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(linux): read the ldconfig cache on non-English systems The startup library check and the new file dialog probe parse `ldconfig -p`, but accepted the listing only when its first line contained "libs found in cache". On a German system the header is "5522 Bibliotheken im Cache ... gefunden", so the cache was treated as unreadable and the check silently fell back to a directory search. Run ldconfig with LC_ALL=C, and accept any listing that starts with a count. Test: a translated header is a valid listing. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * file_dialog_probe: no dead-code errors off Linux Findings, problem and on_path are only used by the Linux probe (and the tests); the empty non-Linux start() was never called. Windows/macOS clippy -D warnings failed on them. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Sonnet 5.5 <[email protected]> Co-authored-by: Brandon Thomas <[email protected]>
This commit is contained in:
6 files changed
+184
-7
No files matched your search
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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")));
|
||||
|
||||
@@ -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 =
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
Reference in new issue
Block a user