Visual Studio Code, rebuilt in Rust
Rust
feat(linux): send title, filters and folder to the portal file chooser
rokartur72a017fdd8ed
diff --git a/native/Cargo.lock b/native/Cargo.lockindex 1433fa94546..b4854cf3083 100644--- a/native/Cargo.lock+++ b/native/Cargo.lock@@ -229,6 +229,7 @@ version = "0.1.0"dependencies = ["alacritty_terminal","anyhow",+ "ashpd","async-openssl","base64 0.22.1","block2 0.6.2",@@ -339,6 +340,7 @@ dependencies = ["futures-channel","futures-util","getrandom 0.4.3",+ "raw-window-handle","serde","serde_repr","wayland-backend",diff --git a/native/crates/app/Cargo.toml b/native/crates/app/Cargo.tomlindex 00a58e7037d..4072ef9a101 100644--- a/native/crates/app/Cargo.toml+++ b/native/crates/app/Cargo.toml@@ -53,6 +53,7 @@ security-framework = "3"[target.'cfg(target_os = "linux")'.dependencies]# The zbus gpui_linux's ashpd and oo7 use.zbus = { version = "5", default-features = false, features = ["async-io", "blocking-api"] }+ashpd = { version = "0.13", default-features = false, features = ["async-io", "file_chooser", "raw_handle", "wayland"] }async-openssl = "0.2"gdkx11 = "0.18"gtk = "0.18"diff --git a/native/crates/app/src/file_dialog.rs b/native/crates/app/src/file_dialog.rsindex 3b4e6b864b4..9f5b564cbef 100644--- a/native/crates/app/src/file_dialog.rs+++ b/native/crates/app/src/file_dialog.rs@@ -1,11 +1,13 @@-//! dialogMainService.ts `showOpenDialog` and `showSaveDialog`: Electron's macOS panels (`macos.rs`); GPUI's path-//! prompts on Linux, which go through the xdg-desktop-portal FileChooser, and in tests.+//! dialogMainService.ts `showOpenDialog` and `showSaveDialog`: Electron's macOS panels (`macos.rs`), the+//! xdg-desktop-portal FileChooser on Linux (`linux.rs`); GPUI's path prompts in tests.use std::path::{Path, PathBuf};use futures::channel::oneshot;use gpui::{App, PathPromptOptions};+#[cfg(target_os = "linux")]+mod linux;#[cfg(target_os = "macos")]mod macos;@@ -30,6 +32,10 @@ pub fn show_open_dialog(dialog: FileDialog, cx: &App) -> oneshot::Receiver<Vec<Pif !cfg!(test) {return macos::show_open_dialog(dialog, cx);}+ #[cfg(target_os = "linux")]+ if !cfg!(test) {+ return gpui_prompt(linux::prompt_for_paths(dialog, cx), cx, |picked| picked.unwrap_or_default());+ }// labels.ts `mnemonicButtonLabel` on Linux: `&&` marks the mnemonic as GTK's `_`.let prompt = dialog.button_label.map(|label| label.replace("&&", "_").into());let picked = cx.prompt_for_paths(PathPromptOptions { files: dialog.files, directories: dialog.folders, multiple: dialog.multiple, prompt });@@ -42,12 +48,17 @@ pub fn show_save_dialog(dialog: FileDialog, cx: &App) -> oneshot::Receiver<Optioif !cfg!(test) {return macos::show_save_dialog(dialog, cx);}+ #[cfg(target_os = "linux")]+ if !cfg!(test) {+ return gpui_prompt(linux::prompt_for_new_path(dialog, cx), cx, |picked| picked.and_then(|paths| paths.into_iter().next()));+ }let (directory, name) = default_location(dialog.default_path.as_deref());let picked = cx.prompt_for_new_path(&directory.unwrap_or_default(), name.as_deref());gpui_prompt(picked, cx, |picked| picked)}-/// GPUI's path prompts, which tests answer with `simulate_new_path_selection`; AppKit panels need the main thread.+/// GPUI's path prompts, which tests answer with `simulate_new_path_selection`, and the portal's; `OpenDialog` holds+/// while either shows.fn gpui_prompt<P: 'static, T: 'static>(picked: oneshot::Receiver<anyhow::Result<Option<P>>>, cx: &App, map: impl FnOnce(Option<P>) -> T + 'static) -> oneshot::Receiver<T> {let (sender, receiver) = oneshot::channel();let open = crate::dialog::OpenDialog::new();diff --git a/native/crates/app/src/file_dialog/linux.rs b/native/crates/app/src/file_dialog/linux.rsnew file mode 100644index 00000000000..efc9826117d--- /dev/null+++ b/native/crates/app/src/file_dialog/linux.rs@@ -0,0 +1,104 @@+//! Chromium's select_file_dialog_linux_portal.cc, which Electron's file dialogs use on Linux: the xdg-desktop-portal+//! FileChooser with the title, the button label, the filters and the default folder, modal to the active window.++use std::path::PathBuf;++use ashpd::WindowIdentifier;+use ashpd::desktop::file_chooser::{FileFilter, OpenFileRequest, SaveFileRequest, SelectedFiles};+use futures::channel::oneshot;+use gpui::{App, AppContext as _, AsyncApp};+use raw_window_handle::{HasDisplayHandle, HasWindowHandle};++use super::{FileDialog, default_location};++pub(super) fn prompt_for_paths(dialog: FileDialog, cx: &App) -> oneshot::Receiver<anyhow::Result<Option<Vec<PathBuf>>>> {+ prompt(cx, async move |identifier| {+ let label = accept_label(&dialog);+ let folder = dialog.default_path.as_deref().and_then(|path| default_location(Some(path)).0);+ OpenFileRequest::default()+ .identifier(identifier)+ .modal(true)+ .title(dialog.title.as_deref())+ .accept_label(label.as_deref())+ .multiple(dialog.multiple)+ .directory(dialog.folders)+ .filters(filters(&dialog))+ .current_folder::<PathBuf>(folder)?+ .send()+ .await?+ .response()+ })+}++pub(super) fn prompt_for_new_path(dialog: FileDialog, cx: &App) -> oneshot::Receiver<anyhow::Result<Option<Vec<PathBuf>>>> {+ prompt(cx, async move |identifier| {+ let label = accept_label(&dialog);+ let (folder, name) = default_location(dialog.default_path.as_deref());+ SaveFileRequest::default()+ .identifier(identifier)+ .modal(true)+ .title(dialog.title.as_deref())+ .accept_label(label.as_deref())+ .current_name(name.as_deref())+ .filters(filters(&dialog))+ .current_folder::<PathBuf>(folder)?+ .send()+ .await?+ .response()+ })+}++/// Sends the request for the active window and reads the picked file URIs; a cancelled chooser is `None`.+fn prompt(cx: &App, request: impl AsyncFnOnce(Option<WindowIdentifier>) -> ashpd::Result<SelectedFiles> + 'static) -> oneshot::Receiver<anyhow::Result<Option<Vec<PathBuf>>>> {+ let (sender, receiver) = oneshot::channel();+ cx.spawn(async move |cx| {+ let identifier = window_identifier(cx).await;+ let picked = match request(identifier).await {+ Ok(files) => Ok(Some(files.uris().iter().filter_map(|uri| url::Url::parse(uri.as_str()).ok()?.to_file_path().ok()).collect())),+ Err(ashpd::Error::Response(ashpd::desktop::ResponseError::Cancelled)) => Ok(None),+ Err(error) => Err(error.into()),+ };+ let _ = sender.send(picked);+ })+ .detach();+ receiver+}++/// `targetWindowId` is the active window; Wayland needs its surface and display, X11 its id.+async fn window_identifier(cx: &mut AsyncApp) -> Option<WindowIdentifier> {+ let active = cx.update(|cx| cx.active_window())?;+ let (window, display) = cx+ .update_window(active, |_, window, _| (HasWindowHandle::window_handle(window).map(|handle| handle.as_raw()), HasDisplayHandle::display_handle(window).map(|handle| handle.as_raw())))+ .ok()?;+ WindowIdentifier::from_raw_handle(&window.ok()?, display.ok().as_ref()).await+}++/// labels.ts `mnemonicButtonLabel` on Linux: `&&` marks the mnemonic as GTK's `_`.+fn accept_label(dialog: &FileDialog) -> Option<String> {+ dialog.button_label.as_ref().map(|label| label.replace("&&", "_"))+}++/// Electron's `{ name, extensions }` filters as `*.extension` globs; `*` matches every file.+fn filters(dialog: &FileDialog) -> Vec<FileFilter> {+ let mut filters = Vec::new();+ for (name, extensions) in &dialog.filters {+ let mut filter = FileFilter::new(name);+ for extension in extensions {+ filter = filter.glob(&if extension == "*" { "*".to_string() } else { format!("*.{extension}") });+ }+ filters.push(filter);+ }+ filters+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn filters_become_globs_and_mnemonics_gtk_underscores() {+ let dialog = FileDialog { button_label: Some("&&Open".into()), filters: vec![("Images".into(), vec!["png".into(), "jpg".into()]), ("All Files".into(), vec!["*".into()])], ..FileDialog::default() };+ assert_eq!(filters(&dialog), vec![FileFilter::new("Images").glob("*.png").glob("*.jpg"), FileFilter::new("All Files").glob("*")]);+ assert_eq!(accept_label(&dialog).as_deref(), Some("_Open"));+ }+}diff --git a/port/ledger.md b/port/ledger.mdindex 73bf4a3093e..5a809721152 100644--- a/port/ledger.md+++ b/port/ledger.md@@ -54,7 +54,7 @@ Status: `open`, `in progress`, `waiting on Artur`, `later` (postponed), `done`,| M23 Linux | app/src/keyboard_layout/linux.rs:8 | open | [linux M] keyboard layout info and raw mapping (xkbcommon). Linux shows now: empty layout, US scan code fallback. | || M23 Linux | app/src/workbench/host.rs:330 | done | [linux S] always on top. | `cargo test -p app always_on_top` on Linux: `always_on_top_toggles_the_context_key_on_linux`; the `_NET_WM_STATE_ABOVE` request (Chromium's X11Window `SetZOrderLevel`) not run under a window manager, Wayland keeps only the state as Chromium || M23 Linux | app/src/workbench/accessibility.rs:531 | done | [linux S] screen reader and reduced motion detection (AT-SPI, portal). | AT-SPI `ScreenReaderEnabled` and the portal's `enable-animations` over D-Bus; not run on a desktop |-| M23 Linux | app/src/file_dialog.rs:28 | open | [linux S] dialog title, filters and the open dialog's default folder in the portal file chooser (GPUI's `PathPromptOptions` carries only the button label, which it now gets). Linux shows now: the portal chooser's title, no filters, its last folder. | |+| M23 Linux | app/src/file_dialog/linux.rs:14 | done | [linux S] dialog title, filters and the open dialog's default folder in the portal file chooser, as Chromium's select_file_dialog_linux_portal.cc sends them (ashpd). | `cargo gc test -p app file_dialog` on Linux: `filters_become_globs_and_mnemonics_gtk_underscores`; the portal request not run on a desktop || M23 Linux | exthost/src/request/linux.rs:24 | done | [linux S] the `<local>` proxy bypass rule. | `cargo test -p exthost request::linux` on Linux: `local_bypasses_hosts_without_a_dot` || M23 Linux | app/src/workbench/shell_command.rs:65 | done | [linux S] `code` CLI install to `~/.local/bin`. | `cargo test -p app shell_command` on Linux || M23 Linux | app/src/update/install.rs:51 | done | [linux M] updates as a download link (no in-place install). | `cargo test -p app update::` on Linux: `an_update_found_on_linux_waits_and_download_opens_its_link` |