Skip to content

Visual Studio Code, rebuilt in Rust

Rust
4.5 KB
Raw Blame
//! 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"));
    }
}