Skip to content

Visual Studio Code, rebuilt in Rust

Rust
8.4 KB
Raw Blame
//! dialogMainService.ts `showOpenDialog` and `showSaveDialog`: Electron's macOS panels (`macos.rs`), the
//! xdg-desktop-portal FileChooser on Linux (`linux.rs`), the Win32 common item dialogs on Windows (`windows.rs`); GPUI's
//! path prompts in tests.

#[cfg(any(target_os = "macos", target_os = "windows"))]
use std::cell::RefCell;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use std::collections::HashSet;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use std::hash::{DefaultHasher, Hash, Hasher};
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;
#[cfg(target_os = "windows")]
mod windows;

/// Options of both panels; the `files`, `folders` and `multiple` flags only count for the open panel.
#[derive(Clone, Debug, Default, Hash, PartialEq)]
pub struct FileDialog {
    pub title: Option<String>,
    pub button_label: Option<String>,
    /// `{ name, extensions }` pairs; the first one applies, more than one adds the Format picker.
    pub filters: Vec<(String, Vec<String>)>,
    pub default_path: Option<PathBuf>,
    pub files: bool,
    pub folders: bool,
    pub multiple: bool,
    /// `treatPackageAsDirectory`, which `doPick` adds on macOS.
    pub packages_as_directories: bool,
}

/// The picked paths, empty when cancelled or when the same dialog already shows for this window.
pub fn show_open_dialog(dialog: FileDialog, cx: &App) -> oneshot::Receiver<Vec<PathBuf>> {
    #[cfg(target_os = "macos")]
    if !cfg!(test) {
        return macos::show_open_dialog(dialog, cx);
    }
    #[cfg(target_os = "windows")]
    if !cfg!(test) {
        return windows::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 });
    gpui_prompt(picked, cx, |picked| picked.unwrap_or_default())
}

/// The picked path, `None` when cancelled or when the same dialog already shows for this window.
pub fn show_save_dialog(dialog: FileDialog, cx: &App) -> oneshot::Receiver<Option<PathBuf>> {
    #[cfg(target_os = "macos")]
    if !cfg!(test) {
        return macos::show_save_dialog(dialog, cx);
    }
    #[cfg(target_os = "windows")]
    if !cfg!(test) {
        return windows::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`, 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();
    cx.foreground_executor()
        .spawn(async move {
            let picked = picked.await.ok().and_then(Result::ok).flatten();
            drop(open);
            let _ = sender.send(map(picked));
        })
        .detach();
    receiver
}

#[cfg(any(target_os = "macos", target_os = "windows"))]
thread_local! {
    /// `windowFileDialogLocks`: the window and options hash of every dialog showing.
    static LOCKS: RefCell<HashSet<(usize, u64)>> = RefCell::default();
}

/// dialogMainService.ts `acquireFileDialogLock`, released when dropped.
#[cfg(any(target_os = "macos", target_os = "windows"))]
struct FileDialogLock(Option<(usize, u64)>);

#[cfg(any(target_os = "macos", target_os = "windows"))]
impl FileDialogLock {
    /// `None` while a dialog of the same options shows for `window`.
    fn acquire(window: Option<usize>, dialog: &FileDialog) -> Option<Self> {
        // Without a window as many dialogs as needed may show, they are not modal to one.
        let Some(window) = window else { return Some(FileDialogLock(None)) };
        let mut hasher = DefaultHasher::new();
        dialog.hash(&mut hasher);
        let key = (window, hasher.finish());
        if !LOCKS.with_borrow_mut(|locks| locks.insert(key)) {
            eprintln!("[DialogMainService]: file open dialog is already or will be showing for the window with the same configuration");
            return None;
        }
        Some(FileDialogLock(Some(key)))
    }
}

#[cfg(any(target_os = "macos", target_os = "windows"))]
impl Drop for FileDialogLock {
    fn drop(&mut self) {
        if let Some(key) = self.0 {
            LOCKS.with_borrow_mut(|locks| locks.remove(&key));
        }
    }
}

/// A directory opens the panel in it; another path opens in its parent with its name filled in.
fn default_location(path: Option<&Path>) -> (Option<PathBuf>, Option<String>) {
    let Some(path) = path else { return (None, None) };
    if path.is_dir() {
        return (Some(path.to_path_buf()), None);
    }
    let directory = path.is_absolute().then(|| path.parent().map(Path::to_path_buf)).flatten();
    (directory, path.file_name().map(|name| name.to_string_lossy().into_owned()))
}

/// `mnemonicButtonLabel` on macOS: `&&` marks a mnemonic, which mac buttons do not show.
#[cfg(target_os = "macos")]
pub fn strip_mnemonic(label: &str) -> String {
    label.replace("&&", "")
}

/// file_dialog_win.cc `ConvertFilters`: `(name, "*.ts;*.js")` per filter, `All Files (*.*)` when there is none.
#[cfg(any(target_os = "windows", test))]
fn filter_specs(filters: &[(String, Vec<String>)]) -> Vec<(String, String)> {
    if filters.is_empty() {
        return vec![("All Files (*.*)".to_owned(), "*.*".to_owned())];
    }
    let mut specs = Vec::new();
    for (name, extensions) in filters {
        let patterns: Vec<String> = extensions.iter().map(|extension| format!("*.{extension}")).collect();
        specs.push((name.clone(), patterns.join(";")));
    }
    specs
}

/// `ApplySettings`: the first filter other than `*.*` is selected and its spec is the default extension.
#[cfg(any(target_os = "windows", test))]
fn default_filter(specs: &[(String, String)]) -> Option<usize> {
    specs.iter().position(|(_, spec)| spec != "*.*")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_default_file_opens_its_folder_with_its_name() {
        let folder = std::env::temp_dir();
        assert_eq!(default_location(Some(&folder)), (Some(folder.clone()), None));
        assert_eq!(default_location(Some(&folder.join("no-such-file.txt"))), (Some(folder), Some("no-such-file.txt".to_owned())));
        assert_eq!(default_location(Some(Path::new("name.txt"))), (None, Some("name.txt".to_owned())));
    }

    #[test]
    fn windows_filters_become_semicolon_specs_and_the_first_specific_one_is_selected() {
        let filters = vec![("All Files".to_owned(), vec!["*".to_owned()]), ("TypeScript".to_owned(), vec!["ts".to_owned(), "tsx".to_owned()])];
        let specs = filter_specs(&filters);
        assert_eq!(specs, vec![("All Files".to_owned(), "*.*".to_owned()), ("TypeScript".to_owned(), "*.ts;*.tsx".to_owned())]);
        assert_eq!(default_filter(&specs), Some(1));
        let none = filter_specs(&[]);
        assert_eq!(none, vec![("All Files (*.*)".to_owned(), "*.*".to_owned())]);
        assert_eq!(default_filter(&none), None);
    }

    #[cfg(any(target_os = "macos", target_os = "windows"))]
    #[test]
    fn one_dialog_of_the_same_options_per_window() {
        let dialog = FileDialog { title: Some("Open".into()), ..FileDialog::default() };
        let lock = FileDialogLock::acquire(Some(1), &dialog).unwrap();
        assert!(FileDialogLock::acquire(Some(1), &dialog).is_none());
        assert!(FileDialogLock::acquire(Some(2), &dialog).is_some());
        assert!(FileDialogLock::acquire(Some(1), &FileDialog::default()).is_some());
        assert!(FileDialogLock::acquire(None, &dialog).is_some() && FileDialogLock::acquire(None, &dialog).is_some());
        drop(lock);
        assert!(FileDialogLock::acquire(Some(1), &dialog).is_some());
    }
}