SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Desktop: the file chooser says when it is not the desktop's own (#10618)
Homero Thompsond03463326557
diff --git a/apps/solidcraft/src/desktop_chooser.rs b/apps/solidcraft/src/desktop_chooser.rsnew file mode 100644index 0000000000..b9873592fc--- /dev/null+++ b/apps/solidcraft/src/desktop_chooser.rs@@ -0,0 +1,100 @@+//! Is the file chooser that opens the desktop's own? (#10159)+//!+//! `rfd` opens the file chooser through the XDG desktop portal; without the portal it falls+//! back to zenity, a window that does not belong to the app and that the app never mentions.+//! The desktop's own chooser is the portal one, so the app has to know when it is not the one+//! that opens, and say so in the session log.+//!+//! The session bus is asked once, on a thread of its own: a bus that answers late must not+//! hold the window. What it answered is kept, and read when a file is opened.++use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};++/// The portal's bus name: the desktop's own file chooser lives behind it.+const PORTAL: &str = "org.freedesktop.portal.Desktop";++/// The bus has not answered yet.+const UNKNOWN: u8 = 0;+/// There is no session bus to reach the portal on.+const NO_SESSION_BUS: u8 = 1;+/// The bus is there but the portal does not answer on it.+const NO_PORTAL_SERVICE: u8 = 2;+/// The bus is there and the portal answers on it.+const PORTAL_THERE: u8 = 3;++/// What the session bus said about the portal.+static BUS: AtomicU8 = AtomicU8::new(UNKNOWN);+/// A file chooser is opening: whether it is the desktop's own is to be said.+static OPENING: AtomicBool = AtomicBool::new(false);++/// Ask the session bus, on a thread of its own, whether the portal is there.+pub fn start(ctx: &egui::Context) {+ let thread_ctx = ctx.clone();+ let probe = move || {+ let answer = match session_bus() {+ None => NO_SESSION_BUS,+ Some(connection) => match portal_on(&connection) {+ true => PORTAL_THERE,+ false => NO_PORTAL_SERVICE,+ },+ };+ BUS.store(answer, Ordering::Relaxed);+ // The answer is in: a file chooser waiting for it can be told now.+ thread_ctx.request_repaint();+ };+ if let Err(e) = std::thread::Builder::new().name("desktop-chooser".into()).spawn(probe) {+ log::warn!("file chooser: no thread to ask the session bus: {e}");+ // Nothing will answer: the desktop's own chooser cannot be told apart from the start.+ BUS.store(PORTAL_THERE, Ordering::Relaxed);+ }+}++/// The session bus, when there is one to talk to.+fn session_bus() -> Option<zbus::blocking::Connection> {+ zbus::blocking::Connection::session().ok()+}++/// Whether the portal answers on the bus: it is either running on it or waiting to be started.+fn portal_on(connection: &zbus::blocking::Connection) -> bool {+ let Ok(bus) = zbus::blocking::fdo::DBusProxy::new(connection) else { return false };+ let named = |names: Vec<zbus::names::OwnedBusName>| names.iter().any(|name| name.as_str() == PORTAL);+ // A portal that is running is on the bus; one that is not running yet is still there when+ // the bus can start it, which is what the portal's service file is for.+ match (bus.list_names().map(named), bus.list_activatable_names().map(named)) {+ (Ok(running), Ok(startable)) => running || startable,+ (Ok(running), Err(_)) => running,+ (Err(_), Ok(startable)) => startable,+ // The bus does not answer: nothing answers on it.+ (Err(_), Err(_)) => false,+ }+}++/// A file chooser is opening: ask for a frame, so that the reason it is not the desktop's own+/// is said (#10159).+pub fn note_opening(ctx: &egui::Context) {+ OPENING.store(true, Ordering::Relaxed);+ ctx.request_repaint();+}++/// The reason the file chooser that is opening is not the desktop's own, if it is not.+///+/// The decision is the one the test states: without a session bus there is no bus to reach the+/// portal on; with a bus but no portal on it, `rfd` falls back to zenity; and under XWayland the+/// window is an X11 one while the session is a Wayland one, which the portal refuses to parent+/// its chooser to.+pub fn take_reason() -> Option<&'static str> {+ if !OPENING.load(Ordering::Relaxed) {+ return None;+ }+ let (dbus_session, portal_service) = match BUS.load(Ordering::Relaxed) {+ NO_SESSION_BUS => (false, false),+ NO_PORTAL_SERVICE => (true, false),+ PORTAL_THERE => (true, true),+ // The bus has not answered yet: wait for it, and say nothing yet.+ _ => return None,+ };+ OPENING.store(false, Ordering::Relaxed);+ let wayland_display = std::env::var_os("WAYLAND_DISPLAY").is_some();+ let x11_display = super::window_system_now() == Some("x11");+ super::desktop_chooser_fallback(dbus_session, portal_service, wayland_display, x11_display)+}diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rsindex e78182203a..05d18eec51 100644--- a/apps/solidcraft/src/main.rs+++ b/apps/solidcraft/src/main.rs@@ -23,6 +23,8 @@ mod app_icon;mod come_forward;mod control_server;#[cfg(target_os = "linux")]+mod desktop_chooser;+#[cfg(target_os = "linux")]mod desktop_theme;#[cfg(any(target_os = "windows", target_os = "macos"))]mod desktop_transparency;@@ -242,6 +244,12 @@ impl eframe::App for App {menu.tick(&mut self.solve, ctx);}self.solve.logic(ctx);+ // The file chooser that opened is not the desktop's own: the user has to be told (#10159).+ #[cfg(target_os = "linux")]+ if let Some(reason) = desktop_chooser::take_reason() {+ let text = self.solve.tr(reason).to_string();+ self.solve.set_status(text, false);+ }self.dialog_folder.design(self.solve.session.path.as_deref());#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]if !self.solve.file_picker_busy() {@@ -471,12 +479,19 @@ fn fullscreen_content_insets(raw: &mut egui::RawInput, title_height: f32, zoom:fn services(cc: &eframe::CreationContext<'_>, folder: &DialogFolder) -> Services {let parent = rfd::AsyncFileDialog::new().set_parent(cc);+ // The file chooser that opens may not be the desktop's own: the user is told when it does+ // not (#10159).+ #[cfg(target_os = "linux")]+ let chooser_ctx = cc.egui_ctx.clone();let open_parent = parent.clone();let program_parent = parent.clone();let file_parent = parent.clone();let (open_folder, file_folder, save_folder) = (folder.clone(), folder.clone(), folder.clone());Services {pick_open: Some(Box::new(move |first: &[&str]| {+ // The chooser that opens may not be the desktop's own (#10159).+ #[cfg(target_os = "linux")]+ desktop_chooser::note_opening(&chooser_ctx);// The file type the command reads comes first, so the picker opens on it (#1801).let mut dialog = open_folder.start(open_parent.clone());if !first.is_empty() {@@ -1109,6 +1124,10 @@ fn main() -> eframe::Result {solidcraft_ui_egui::fonts::load_system_fonts_in_background(&cc.egui_ctx);mark("fonts");let dialog_folder = DialogFolder::default();+ // The file chooser that opens may not be the desktop's own: the session bus is asked+ // now, so the answer is there when a file is opened (#10159).+ #[cfg(target_os = "linux")]+ desktop_chooser::start(&cc.egui_ctx);let mut app = SolveApp::new(Session::default(), services(cc, &dialog_folder));app.apply_off_thread = Some(solidcraft_ui_egui::dialogs::APPLY_AT_ONCE);app.custom_titlebar = custom_titlebar;@@ -1439,6 +1458,47 @@ fn prefer_x11(display: bool, wayland_display: bool, desktop: Option<&str>, wayladisplay && !(niri && wayland_display)}+#[cfg(all(unix, not(target_os = "macos")))]+const CHOOSER_NO_SESSION_BUS: &str = "file.open.portal_fallback.no_session_bus";+#[cfg(all(unix, not(target_os = "macos")))]+const CHOOSER_NO_PORTAL_SERVICE: &str = "file.open.portal_fallback.no_portal_service";+#[cfg(all(unix, not(target_os = "macos")))]+const CHOOSER_XWAYLAND: &str = "file.open.portal_fallback.xwayland";++/// Whether the chooser that opens is NOT the desktop's own, and why.+///+/// `rfd` opens the file chooser through the XDG desktop portal; when the portal is not there it+/// falls back to zenity, which opens a window that does not belong to SolidCraft and that the+/// application never mentions. The application has to know that: this decision is what the warning+/// is built on.+///+/// * `dbus_session`: the session bus is there (`DBUS_SESSION_BUS_ADDRESS`).+/// * `portal_service`: the file chooser portal answers on it.+/// * `wayland_display`: a Wayland session runs (`WAYLAND_DISPLAY`).+/// * `x11_display`: the window is an X11 one (`DISPLAY`, or XWayland).+///+/// `None` means the desktop's own chooser is the one that opens and there is nothing to say;+/// `Some` carries the reason to report.+#[cfg(all(unix, not(target_os = "macos")))]+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn desktop_chooser_fallback(dbus_session: bool, portal_service: bool, wayland_display: bool, x11_display: bool) -> Option<&'static str> {+ // Without a session bus there is no bus to reach the portal on, so the chooser is not the+ // desktop's own whatever else is there.+ if !dbus_session {+ return Some(CHOOSER_NO_SESSION_BUS);+ }+ // The bus is there but the portal does not answer on it: `rfd` falls back to zenity.+ if !portal_service {+ return Some(CHOOSER_NO_PORTAL_SERVICE);+ }+ // Under XWayland the window is an X11 one while the session is a Wayland one, and the portal+ // refuses to parent its chooser to an X11 window: `rfd` falls back to zenity.+ if wayland_display && x11_display {+ return Some(CHOOSER_XWAYLAND);+ }+ None+}+#[cfg(all(test, unix, not(target_os = "macos")))]mod backend_tests {use super::prefer_x11;@@ -1474,6 +1534,30 @@ mod backend_tests {assert!(prefer_x11(true, true, Some("niri"), over(Some("x11"))));}+ /// The file chooser must say when it is NOT the desktop's own: `rfd` falls back to zenity+ /// when the XDG portal is not there, and the user gets a foreign window with no explanation.+ #[test]+ fn the_file_picker_says_when_it_is_not_the_desktops_own_chooser() {+ use super::desktop_chooser_fallback;+ // The normal case: the portal is there, the desktop's own chooser opens, nothing to say.+ assert_eq!(desktop_chooser_fallback(true, true, true, false), None);+ // No session bus: the portal can not be reached at all, so `rfd` falls back to zenity.+ assert!(+ desktop_chooser_fallback(false, true, true, false).is_some(),+ "without a D-Bus session bus the file chooser is not the desktop's own: the user has to be told"+ );+ // The bus is there but the portal service is not: same fallback, same warning.+ assert!(+ desktop_chooser_fallback(true, false, true, false).is_some(),+ "without the desktop portal service the file chooser is not the desktop's own: the user has to be told"+ );+ // XWayland: the parent window is an X11 one and the portal refuses it, so `rfd` falls back.+ assert!(+ desktop_chooser_fallback(true, true, true, true).is_some(),+ "under XWayland the portal rejects the parent window: the user has to be told"+ );+ }+#[test]fn the_desktops_title_bar_only_when_asked_for() {use super::titlebar_choice;diff --git a/assets/locales/pending/file-picker-portal-fallback.json b/assets/locales/pending/file-picker-portal-fallback.jsonnew file mode 100644index 0000000000..f22711d49d--- /dev/null+++ b/assets/locales/pending/file-picker-portal-fallback.json@@ -0,0 +1,42 @@+{+ "en": {+ "file.open.portal_fallback.no_session_bus": "The file chooser that opened is not the desktop's own: there is no D-Bus session bus.",+ "file.open.portal_fallback.no_portal_service": "The file chooser that opened is not the desktop's own: the desktop portal service is not available.",+ "file.open.portal_fallback.xwayland": "The file chooser that opened is not the desktop's own: under XWayland the portal refuses the parent window."+ },+ "ar": {+ "file.open.portal_fallback.no_session_bus": "منتقي الملفات الذي فُتح ليس تابعًا لسطح المكتب: لا يوجد ناقل جلسات D-Bus.",+ "file.open.portal_fallback.no_portal_service": "منتقي الملفات الذي فُتح ليس تابعًا لسطح المكتب: خدمة منتقي الملفات في سطح المكتب غير متاحة.",+ "file.open.portal_fallback.xwayland": "منتقي الملفات الذي فُتح ليس تابعًا لسطح المكتب: في XWayland ترفض البوابة النافذة الأصلية."+ },+ "de": {+ "file.open.portal_fallback.no_session_bus": "Die geöffnete Dateiauswahl ist nicht die des Desktops: Es gibt keinen D-Bus-Sitzungsbus.",+ "file.open.portal_fallback.no_portal_service": "Die geöffnete Dateiauswahl ist nicht die des Desktops: Der Dateiauswahl-Dienst des Desktops ist nicht verfügbar.",+ "file.open.portal_fallback.xwayland": "Die geöffnete Dateiauswahl ist nicht die des Desktops: Unter XWayland lehnt das Portal das Elternfenster ab."+ },+ "he": {+ "file.open.portal_fallback.no_session_bus": "בורר הקבצים שנפתח אינו של שולחן העבודה: אין אוטובוס הפעלה של D-Bus.",+ "file.open.portal_fallback.no_portal_service": "בורר הקבצים שנפתח אינו של שולחן העבודה: שירות בחירת הקבצים של שולחן העבודה אינו זמין.",+ "file.open.portal_fallback.xwayland": "בורר הקבצים שנפתח אינו של שולחן העבודה: תחת XWayland הפורטל דוחה את חלון האב."+ },+ "ja": {+ "file.open.portal_fallback.no_session_bus": "開いたファイル選択はデスクトップのものではありません。D-Bus セッションがありません。",+ "file.open.portal_fallback.no_portal_service": "開いたファイル選択はデスクトップのものではありません。デスクトップのファイル選択サービスが利用できません。",+ "file.open.portal_fallback.xwayland": "開いたファイル選択はデスクトップのものではありません。XWayland ではポータルが親ウィンドウを拒否します。"+ },+ "ko": {+ "file.open.portal_fallback.no_session_bus": "열린 파일 선택은 데스크톱의 것이 아닙니다: D-Bus 세션 버스가 없습니다.",+ "file.open.portal_fallback.no_portal_service": "열린 파일 선택은 데스크톱의 것이 아닙니다: 데스크톱의 파일 선택 서비스를 사용할 수 없습니다.",+ "file.open.portal_fallback.xwayland": "열린 파일 선택은 데스크톱의 것이 아닙니다: XWayland에서는 포털이 부모 창을 거부합니다."+ },+ "vi": {+ "file.open.portal_fallback.no_session_bus": "Bộ chọn tệp đã mở không phải của riêng desktop: không có bus phiên D-Bus.",+ "file.open.portal_fallback.no_portal_service": "Bộ chọn tệp đã mở không phải của riêng desktop: dịch vụ chọn tệp của desktop không khả dụng.",+ "file.open.portal_fallback.xwayland": "Bộ chọn tệp đã mở không phải của riêng desktop: dưới XWayland, portal từ chối cửa sổ cha."+ },+ "zh": {+ "file.open.portal_fallback.no_session_bus": "打开的文件选择器并非桌面自带:没有 D-Bus 会话总线。",+ "file.open.portal_fallback.no_portal_service": "打开的文件选择器并非桌面自带:桌面的文件选择服务不可用。",+ "file.open.portal_fallback.xwayland": "打开的文件选择器并非桌面自带:在 XWayland 下,门户会拒绝父窗口。"+ }+}