Skip to content

Visual Studio Code, rebuilt in Rust

Rust
5.5 KB
Raw Blame
//! Electron's file_dialog_win.cc: an IFileOpenDialog or IFileSaveDialog owned by the active window, with the title,
//! the button label, the filters and the default path of `ApplySettings`.

use std::path::PathBuf;

use futures::channel::oneshot;
use gpui::App;
use windows::Win32::Foundation::HWND;
use windows::Win32::System::Com::{CLSCTX_ALL, CoCreateInstance, CoTaskMemFree};
use windows::Win32::UI::Input::KeyboardAndMouse::GetActiveWindow;
use windows::Win32::UI::Shell::Common::COMDLG_FILTERSPEC;
use windows::Win32::UI::Shell::{
    FOS_ALLOWMULTISELECT, FOS_FILEMUSTEXIST, FOS_FORCEFILESYSTEM, FOS_OVERWRITEPROMPT, FOS_PATHMUSTEXIST, FOS_PICKFOLDERS, FileOpenDialog, FileSaveDialog, IFileDialog, IFileOpenDialog, IFileSaveDialog, IShellItem, SHCreateItemFromParsingName, SIGDN_FILESYSPATH,
};
use windows::core::{HSTRING, PCWSTR};

use super::{FileDialog, FileDialogLock, default_filter, default_location, filter_specs};

pub(super) fn show_open_dialog(mut dialog: FileDialog, cx: &App) -> oneshot::Receiver<Vec<PathBuf>> {
    // dialogMainService.ts: "Ensure the path exists (if provided)".
    if dialog.default_path.as_ref().is_some_and(|path| !path.exists()) {
        dialog.default_path = None;
    }
    show(dialog, cx, open)
}

pub(super) fn show_save_dialog(dialog: FileDialog, cx: &App) -> oneshot::Receiver<Option<PathBuf>> {
    show(dialog, cx, save)
}

/// `acquireFileDialogLock`, then the dialog modal to the active window (`targetWindowId`), shown after this update
/// returns; a failed or cancelled dialog answers nothing, as `ShowOpenDialogSync` returns false for any failed HRESULT.
fn show<T: Default + 'static>(dialog: FileDialog, cx: &App, run: fn(&FileDialog, Option<HWND>) -> windows::core::Result<T>) -> oneshot::Receiver<T> {
    let (sender, receiver) = oneshot::channel();
    // SAFETY: reads the calling thread's active window, GPUI's windows live on this thread.
    let owner = Some(unsafe { GetActiveWindow() }).filter(|owner| !owner.is_invalid());
    let Some(lock) = FileDialogLock::acquire(owner.map(|owner| owner.0 as usize), &dialog) else {
        let _ = sender.send(T::default());
        return receiver;
    };
    let open = crate::dialog::OpenDialog::new();
    cx.foreground_executor()
        .spawn(async move {
            let picked = run(&dialog, owner).unwrap_or_default();
            drop((lock, open));
            let _ = sender.send(picked);
        })
        .detach();
    receiver
}

fn open(dialog: &FileDialog, owner: Option<HWND>) -> windows::core::Result<Vec<PathBuf>> {
    let mut options = FOS_FORCEFILESYSTEM | FOS_FILEMUSTEXIST;
    if dialog.folders {
        options |= FOS_PICKFOLDERS;
    }
    if dialog.multiple {
        options |= FOS_ALLOWMULTISELECT;
    }
    // SAFETY: COM calls on the main thread, which GPUI's platform initialized with OleInitialize.
    unsafe {
        let picker: IFileOpenDialog = CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)?;
        picker.SetOptions(options)?;
        apply_settings(&picker, dialog);
        picker.Show(owner)?;
        let items = picker.GetResults()?;
        let mut paths = Vec::new();
        for index in 0..items.GetCount()? {
            paths.push(item_path(&items.GetItemAt(index)?)?);
        }
        Ok(paths)
    }
}

fn save(dialog: &FileDialog, owner: Option<HWND>) -> windows::core::Result<Option<PathBuf>> {
    // SAFETY: as in `open`.
    unsafe {
        let picker: IFileSaveDialog = CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)?;
        picker.SetOptions(FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST | FOS_OVERWRITEPROMPT)?;
        apply_settings(&picker, dialog);
        picker.Show(owner)?;
        Ok(Some(item_path(&picker.GetResult()?)?))
    }
}

/// `ApplySettings`, which ignores the HRESULTs of these calls.
unsafe fn apply_settings(picker: &IFileDialog, dialog: &FileDialog) {
    let (folder, name) = default_location(dialog.default_path.as_deref());
    let specs = filter_specs(&dialog.filters);
    let wide: Vec<(HSTRING, HSTRING)> = specs.iter().map(|(name, spec)| (HSTRING::from(name), HSTRING::from(spec))).collect();
    let filter_specs: Vec<COMDLG_FILTERSPEC> = wide.iter().map(|(name, spec)| COMDLG_FILTERSPEC { pszName: PCWSTR(name.as_ptr()), pszSpec: PCWSTR(spec.as_ptr()) }).collect();
    // SAFETY: the strings outlive the calls, which copy them.
    unsafe {
        let _ = picker.SetFileName(&HSTRING::from(name.unwrap_or_default()));
        if let Some(title) = &dialog.title {
            let _ = picker.SetTitle(&HSTRING::from(title));
        }
        if let Some(label) = &dialog.button_label {
            let _ = picker.SetOkButtonLabel(&HSTRING::from(crate::dialog::windows_mnemonic(label)));
        }
        let _ = picker.SetFileTypes(&filter_specs);
        if let Some(index) = default_filter(&specs) {
            // SetFileTypeIndex is one-based.
            let _ = picker.SetFileTypeIndex(index as u32 + 1);
            let _ = picker.SetDefaultExtension(&wide[index].1);
        }
        if let Some(folder) = folder
            && let Ok(item) = SHCreateItemFromParsingName::<_, _, IShellItem>(&HSTRING::from(folder.as_path()), None)
        {
            let _ = picker.SetFolder(&item);
        }
    }
}

unsafe fn item_path(item: &IShellItem) -> windows::core::Result<PathBuf> {
    // SAFETY: the name is the shell's allocation, freed once read.
    unsafe {
        let name = item.GetDisplayName(SIGDN_FILESYSPATH)?;
        let path = PathBuf::from(name.to_hstring().to_os_string());
        CoTaskMemFree(Some(name.0 as _));
        Ok(path)
    }
}