Skip to content

Visual Studio Code, rebuilt in Rust

Rust

feat(windows): add Win32 file dialogs and task dialog message boxes

rokarture24ef5f47bcc
diff --git a/native/Cargo.lock b/native/Cargo.lock
index 551afb933e0..4a7c8f4c45f 100644
--- a/native/Cargo.lock
+++ b/native/Cargo.lock
@@ -271,6 +271,7 @@ dependencies = [
"ttf-parser",
"url",
"webkit2gtk",
+ "windows 0.61.3",
"windows-sys 0.61.2",
"wuff",
"x11",
diff --git a/native/crates/app/Cargo.toml b/native/crates/app/Cargo.toml
index 65b3dd6ba99..5d8fa9a56de 100644
--- a/native/crates/app/Cargo.toml
+++ b/native/crates/app/Cargo.toml
@@ -51,6 +51,16 @@ objc2-web-kit = { version = "0.3.2", default-features = false, features = ["WKCo
security-framework = "3"
[target.'cfg(target_os = "windows")'.dependencies]
+# GPUI's version, for the COM interfaces windows-sys lacks.
+windows = { version = "0.61", features = [
+ "Win32_Foundation",
+ "Win32_System_Com",
+ "Win32_System_LibraryLoader",
+ "Win32_UI_Controls",
+ "Win32_UI_Input_KeyboardAndMouse",
+ "Win32_UI_Shell",
+ "Win32_UI_Shell_Common",
+] }
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_Security",
diff --git a/native/crates/app/src/dialog.rs b/native/crates/app/src/dialog.rs
index 780f48c4216..0733ca18546 100644
--- a/native/crates/app/src/dialog.rs
+++ b/native/crates/app/src/dialog.rs
@@ -1,9 +1,11 @@
//! `nativeHostService.showMessageBox` with a checkbox: Electron's macOS message box is an NSAlert sheet whose
-//! suppression button carries `checkboxLabel`, its Linux one a GTK message dialog with a check button (linux.rs).
-//! GPUI's `Window::prompt` has neither.
+//! suppression button carries `checkboxLabel`, its Linux one a GTK message dialog with a check button (linux.rs), its
+//! Windows one a task dialog with verification text (windows.rs). GPUI's `Window::prompt` has neither.
#[cfg(target_os = "linux")]
mod linux;
+#[cfg(target_os = "windows")]
+mod windows;
use std::cell::Cell;
@@ -75,6 +77,8 @@ pub fn show_message_box_with_checkbox(window: &Window, in_tests: InTests, level:
let ns_window = app_kit_window(window);
#[cfg(target_os = "linux")]
let x_window = crate::webview::supported().then(|| crate::webview::gpui_x_window(window));
+ #[cfg(target_os = "windows")]
+ let owner = windows::owner(window);
#[cfg(target_os = "linux")]
let native_box = x_window.is_some();
#[cfg(not(target_os = "linux"))]
@@ -109,11 +113,53 @@ pub fn show_message_box_with_checkbox(window: &Window, in_tests: InTests, level:
if let Some(x_window) = x_window {
linux::show(x_window, level, &message, detail.as_deref(), &buttons, checkbox, sender);
}
+ #[cfg(target_os = "windows")]
+ if let Some(owner) = owner {
+ windows::show(owner, level, &message, detail.as_deref(), &buttons, checkbox, sender);
+ }
})
.detach();
receiver
}
+/// labels.ts `mnemonicButtonLabel` on Windows: `&&` marks the mnemonic as `&`, a lone `&` is escaped as `&&`.
+#[cfg(any(target_os = "windows", test))]
+pub(crate) fn windows_mnemonic(label: &str) -> String {
+ let parts: Vec<String> = label.split("&&").map(|part| part.replace('&', "&&")).collect();
+ parts.join("&")
+}
+
+/// message_box_win.cc `kIDStart`: the id of the first custom button.
+#[cfg(any(target_os = "windows", test))]
+const TASK_DIALOG_FIRST_ID: i32 = 100;
+
+/// The task dialog's custom buttons as `(id, label)`, in the caller's order: `massageMessageBoxOptions` on Windows only
+/// moves the cancel button last, where the caller's buttons already have it, and `noLink` keeps them buttons.
+#[cfg(any(target_os = "windows", test))]
+fn task_dialog_buttons(buttons: &[String]) -> Vec<(i32, String)> {
+ let mut shown = Vec::new();
+ for (index, label) in buttons.iter().enumerate() {
+ shown.push((TASK_DIALOG_FIRST_ID + index as i32, windows_mnemonic(label)));
+ }
+ shown
+}
+
+/// message_box_win.cc: a custom button answers its index; Esc, the close button or a failed dialog the cancel
+/// button, the last one.
+#[cfg(any(target_os = "windows", test))]
+fn task_dialog_answer(id: i32, count: usize) -> usize {
+ usize::try_from(id - TASK_DIALOG_FIRST_ID).ok().filter(|index| *index < count).unwrap_or(count.saturating_sub(1))
+}
+
+/// message_box_win.cc: with a detail the message is the main instruction above it, else the content alone.
+#[cfg(any(target_os = "windows", test))]
+fn task_dialog_texts<'a>(message: &'a str, detail: Option<&'a str>) -> (Option<&'a str>, &'a str) {
+ match detail.filter(|detail| !detail.is_empty()) {
+ Some(detail) => (Some(message), detail),
+ None => (None, message),
+ }
+}
+
#[cfg(target_os = "macos")]
fn begin_alert_sheet(ns_window: &NSWindow, level: PromptLevel, message: &str, detail: Option<&str>, buttons: &[String], checkbox: Option<(String, bool)>, sender: oneshot::Sender<(usize, bool)>) {
let sender = Cell::new(Some((sender, OpenDialog::new())));
@@ -171,3 +217,35 @@ pub(crate) fn app_kit_window(window: &Window) -> Option<Retained<NSWindow>> {
let view: &NSView = unsafe { handle.ns_view.cast().as_ref() };
view.window()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn windows_labels_take_ampersand_mnemonics() {
+ assert_eq!(windows_mnemonic("&&Save"), "&Save");
+ assert_eq!(windows_mnemonic("Save && Close"), "Save & Close");
+ assert_eq!(windows_mnemonic("Tom & Jerry"), "Tom && Jerry");
+ assert_eq!(windows_mnemonic("Don't Save"), "Don't Save");
+ }
+
+ #[test]
+ fn windows_task_dialog_keeps_the_callers_button_order_with_cancel_last() {
+ // The unsaved changes prompt: [Save, Don't Save, Cancel] shows as Save, Don't Save, Cancel.
+ let buttons = ["&&Save".to_owned(), "Do&&n't Save".to_owned(), "Cancel".to_owned()];
+ assert_eq!(task_dialog_buttons(&buttons), vec![(100, "&Save".to_owned()), (101, "Do&n't Save".to_owned()), (102, "Cancel".to_owned())]);
+ assert_eq!(task_dialog_answer(101, 3), 1);
+ // IDCANCEL (Esc, the close button) and 0 (TaskDialogIndirect failed) answer cancel.
+ assert_eq!(task_dialog_answer(2, 3), 2);
+ assert_eq!(task_dialog_answer(0, 3), 2);
+ assert_eq!(task_dialog_answer(0, 0), 0);
+ }
+
+ #[test]
+ fn windows_task_dialog_message_is_the_main_instruction_only_with_a_detail() {
+ assert_eq!(task_dialog_texts("Save changes?", Some("Your changes will be lost.")), (Some("Save changes?"), "Your changes will be lost."));
+ assert_eq!(task_dialog_texts("Saved.", None), (None, "Saved."));
+ assert_eq!(task_dialog_texts("Saved.", Some("")), (None, "Saved."));
+ }
+}
diff --git a/native/crates/app/src/dialog/windows.rs b/native/crates/app/src/dialog/windows.rs
new file mode 100644
index 00000000000..ea273b08729
--- /dev/null
+++ b/native/crates/app/src/dialog/windows.rs
@@ -0,0 +1,62 @@
+//! Electron's message_box_win.cc `ShowTaskDialogWstr`: a task dialog owned by the window, with the buttons
+//! `task_dialog_buttons` gives and the checkbox as its verification text.
+
+use std::ffi::c_void;
+
+use futures::channel::oneshot;
+use gpui::{PromptLevel, Window};
+use raw_window_handle::{HasWindowHandle, RawWindowHandle};
+use windows::Win32::Foundation::HWND;
+use windows::Win32::System::LibraryLoader::GetModuleHandleW;
+use windows::Win32::UI::Controls::{
+ TASKDIALOG_BUTTON, TASKDIALOGCONFIG, TASKDIALOGCONFIG_0, TD_ERROR_ICON, TD_INFORMATION_ICON, TD_WARNING_ICON, TDF_ALLOW_DIALOG_CANCELLATION, TDF_POSITION_RELATIVE_TO_WINDOW, TDF_SIZE_TO_CONTENT, TDF_VERIFICATION_FLAG_CHECKED, TaskDialogIndirect,
+};
+use windows::core::{BOOL, HSTRING, PCWSTR};
+
+use super::{OpenDialog, task_dialog_answer, task_dialog_buttons, task_dialog_texts};
+
+/// The window's HWND; none on GPUI's test platform.
+pub fn owner(window: &Window) -> Option<HWND> {
+ let RawWindowHandle::Win32(handle) = HasWindowHandle::window_handle(window).ok()?.as_raw() else { return None };
+ Some(HWND(handle.hwnd.get() as *mut c_void))
+}
+
+/// Shows the dialog modal to `owner` and answers the pressed button's index in `buttons` with the checkbox state.
+pub fn show(owner: HWND, level: PromptLevel, message: &str, detail: Option<&str>, buttons: &[String], checkbox: Option<(String, bool)>, sender: oneshot::Sender<(usize, bool)>) {
+ let _open = OpenDialog::new();
+ let title = HSTRING::from(crate::product::name_long());
+ let (instruction, content) = task_dialog_texts(message, detail);
+ let (instruction, content) = (instruction.map(HSTRING::from), HSTRING::from(content));
+ let labels: Vec<(i32, HSTRING)> = task_dialog_buttons(buttons).into_iter().map(|(id, label)| (id, HSTRING::from(label))).collect();
+ let task_buttons: Vec<TASKDIALOG_BUTTON> = labels.iter().map(|(id, label)| TASKDIALOG_BUTTON { nButtonID: *id, pszButtonText: PCWSTR(label.as_ptr()) }).collect();
+ let verification = checkbox.as_ref().map(|(label, _)| HSTRING::from(label));
+ let mut flags = TDF_SIZE_TO_CONTENT | TDF_ALLOW_DIALOG_CANCELLATION | TDF_POSITION_RELATIVE_TO_WINDOW;
+ if checkbox.is_some_and(|(_, checked)| checked) {
+ flags |= TDF_VERIFICATION_FLAG_CHECKED;
+ }
+ let icon = match level {
+ PromptLevel::Info => TD_INFORMATION_ICON,
+ PromptLevel::Warning => TD_WARNING_ICON,
+ PromptLevel::Critical => TD_ERROR_ICON,
+ };
+ // SAFETY: the module handle of this executable.
+ let module = unsafe { GetModuleHandleW(None) }.unwrap_or_default();
+ let config = TASKDIALOGCONFIG {
+ cbSize: size_of::<TASKDIALOGCONFIG>() as u32,
+ hwndParent: owner,
+ hInstance: module.into(),
+ dwFlags: flags,
+ pszWindowTitle: PCWSTR(title.as_ptr()),
+ Anonymous1: TASKDIALOGCONFIG_0 { pszMainIcon: icon },
+ pszMainInstruction: instruction.as_ref().map_or(PCWSTR::null(), |instruction| PCWSTR(instruction.as_ptr())),
+ pszContent: PCWSTR(content.as_ptr()),
+ cButtons: task_buttons.len() as u32,
+ pButtons: task_buttons.as_ptr(),
+ pszVerificationText: verification.as_ref().map_or(PCWSTR::null(), |label| PCWSTR(label.as_ptr())),
+ ..Default::default()
+ };
+ let (mut id, mut checked) = (0, BOOL(0));
+ // SAFETY: every string and the button array outlive the modal call. A failed dialog leaves `id` 0: cancel.
+ let _ = unsafe { TaskDialogIndirect(&config, Some(&raw mut id), None, Some(&raw mut checked)) };
+ let _ = sender.send((task_dialog_answer(id, buttons.len()), checked.as_bool()));
+}
diff --git a/native/crates/app/src/file_dialog.rs b/native/crates/app/src/file_dialog.rs
index 9f5b564cbef..d710fd31f3e 100644
--- a/native/crates/app/src/file_dialog.rs
+++ b/native/crates/app/src/file_dialog.rs
@@ -1,6 +1,13 @@
//! 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.
+//! 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;
@@ -10,6 +17,8 @@ use gpui::{App, PathPromptOptions};
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)]
@@ -32,6 +41,10 @@ pub fn show_open_dialog(dialog: FileDialog, cx: &App) -> oneshot::Receiver<Vec<P
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());
@@ -48,6 +61,10 @@ pub fn show_save_dialog(dialog: FileDialog, cx: &App) -> oneshot::Receiver<Optio
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()));
@@ -72,6 +89,42 @@ fn gpui_prompt<P: 'static, T: 'static>(picked: oneshot::Receiver<anyhow::Result<
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) };
@@ -88,6 +141,26 @@ 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::*;
@@ -99,4 +172,28 @@ mod tests {
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());
+ }
}
diff --git a/native/crates/app/src/file_dialog/macos.rs b/native/crates/app/src/file_dialog/macos.rs
index 8a0efafbdc0..39a67f1ec76 100644
--- a/native/crates/app/src/file_dialog/macos.rs
+++ b/native/crates/app/src/file_dialog/macos.rs
@@ -1,9 +1,7 @@
//! Electron's file_dialog_mac.mm: an NSOpenPanel or NSSavePanel as a sheet on the window, with the filters, the
//! default path, the button label and the title.
-use std::cell::{Cell, RefCell};
-use std::collections::HashSet;
-use std::hash::{DefaultHasher, Hash, Hasher};
+use std::cell::Cell;
use std::path::PathBuf;
use block2::RcBlock;
@@ -16,12 +14,7 @@ use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, Message, define_clas
use objc2_app_kit::{NSApplication, NSModalResponse, NSModalResponseOK, NSOpenPanel, NSPopUpButton, NSSavePanel, NSTextField, NSView};
use objc2_foundation::{NSArray, NSObject, NSPoint, NSRect, NSSize, NSString, NSURL};
-use super::{FileDialog, default_location, strip_mnemonic};
-
-thread_local! {
- /// `windowFileDialogLocks`: the window and options hash of every panel showing.
- static LOCKS: RefCell<HashSet<(usize, u64)>> = RefCell::default();
-}
+use super::{FileDialog, FileDialogLock, default_location, strip_mnemonic};
pub(super) fn show_open_dialog(mut dialog: FileDialog, cx: &App) -> oneshot::Receiver<Vec<PathBuf>> {
// "Ensure the path exists (if provided)".
@@ -61,21 +54,15 @@ fn show<T: 'static>(dialog: &FileDialog, panel: &NSSavePanel, format: Option<Ret
let mtm = MainThreadMarker::new().expect("dialogs open on the main thread");
let app = NSApplication::sharedApplication(mtm);
let ns_window = app.keyWindow().or_else(|| app.mainWindow());
- let mut hasher = DefaultHasher::new();
- dialog.hash(&mut hasher);
- let lock = (ns_window.as_ref().map_or(0, |window| Retained::as_ptr(window) as usize), hasher.finish());
- // Without a window as many dialogs as needed may show, they are not modal to one.
- if ns_window.is_some() && !LOCKS.with_borrow_mut(|locks| locks.insert(lock)) {
- eprintln!("[DialogMainService]: file open dialog is already or will be showing for the window with the same configuration");
+ let Some(lock) = FileDialogLock::acquire(ns_window.as_ref().map(|window| Retained::as_ptr(window) as usize), dialog) else {
let _ = sender.send(refused);
return receiver;
- }
- let sender = Cell::new(Some((sender, crate::dialog::OpenDialog::new())));
+ };
+ let sender = Cell::new(Some((sender, crate::dialog::OpenDialog::new(), lock)));
let handler = RcBlock::new(move |response: NSModalResponse| {
- LOCKS.with_borrow_mut(|locks| locks.remove(&lock));
// The Format pop-up's target lives as long as its sheet.
let _target = &format;
- if let Some((sender, _open)) = sender.take() {
+ if let Some((sender, _open, _lock)) = sender.take() {
let _ = sender.send(read(response == NSModalResponseOK));
}
});
diff --git a/native/crates/app/src/file_dialog/windows.rs b/native/crates/app/src/file_dialog/windows.rs
new file mode 100644
index 00000000000..ac159bab532
--- /dev/null
+++ b/native/crates/app/src/file_dialog/windows.rs
@@ -0,0 +1,123 @@
+//! 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)
+ }
+}
diff --git a/port/ledger.md b/port/ledger.md
index 98dc0232f58..08058820f20 100644
--- a/port/ledger.md
+++ b/port/ledger.md
@@ -69,8 +69,8 @@ Status: `open`, `in progress`, `waiting on Artur`, `later` (postponed), `done`,
| M24 Windows | port/tools/windows-build:1 | done | [windows M] cross build on the Studio: `cargo gc xwin` with Homebrew llvm and lld on PATH, for `x86_64-pc-windows-msvc` and `aarch64-pc-windows-msvc`; the Unix-only std and libc calls (files/src/disk.rs:58, exthost/src/lib.rs:31, app/src/cli.rs:7, app/src/launch.rs:5, app/src/shell_env.rs:5, app/src/update/install.rs:39) behind `cfg(unix)` with a Windows counterpart or an M24 row naming what Windows shows meanwhile. | `port/tools/windows-build 'cargo gc xwin build -p app --target x86_64-pc-windows-msvc'` and the same for `aarch64-pc-windows-msvc` exit 0 |
| M24 Windows | app/src/terminal/pty.rs:1 | in progress | [windows L] terminal through ConPTY (terminal/pty/conpty.rs, windows-sys), as node-pty's conpty.cc and windowsPtyAgent.ts: spawn with the command line `argsToCommandLine` builds, resize, kill (signals ignored, as node-pty on Windows), `hasChildProcesses` from a process snapshot, cwd as the initial cwd (terminalProcess.ts `getCwd` on Windows). Built, not yet run on Windows; the foreground process is the started file (windowsTerminal.ts `process`), not windowsShellHelper.ts's tracking. | `cargo gc test -p app pty` on the windows runner; `cargo gc test -p app args_to_command_line` on the host, with node-pty lib/windowsPtyAgent.js's output |
| M24 Windows | app/src/terminal/profiles.rs:133 | open | [windows M] Windows terminal profiles (terminalProfiles.ts `detectAvailableWindowsProfiles`): PowerShell (pwsh, then Windows PowerShell), Command Prompt, Git Bash, WSL distributions; `terminal.integrated.defaultProfile.windows`; shell integration for pwsh (shellIntegration.ps1). | `cargo gc test -p app terminal::profiles` on the windows runner |
-| M24 Windows | app/src/file_dialog.rs:9 | open | [windows M] Win32 open and save dialogs (IFileOpenDialog, IFileSaveDialog) with title, filters, default path, folder pick and multi-select, as Chromium's select_file_dialog_win.cc gets them from Electron's file_dialog_win.cc (filter specs `*.ts;*.js`, `All Files (*.*)`). | `cargo gc test -p app file_dialog` on the host for the filter specs; the dialog not run on a desktop |
-| M24 Windows | app/src/dialog.rs:5 | open | [windows M] native message box through TaskDialogIndirect, as Electron's message_box_win.cc: buttons in the order dialogs.ts `massageMessageBoxOptions` gives Windows, the checkbox as the verification text, owner window modal. | `cargo gc test -p app dialog` on the host for the button order; the dialog on the windows runner |
+| M24 Windows | app/src/file_dialog.rs:9 | in progress | [windows M] Win32 open and save dialogs (file_dialog/windows.rs, IFileOpenDialog, IFileSaveDialog) with title, button label (`&` mnemonic), filters, default path, folder pick and multi-select, as Electron's file_dialog_win.cc `ApplySettings` and `ConvertFilters` (filter specs `*.ts;*.js`, `All Files (*.*)`, the first specific filter selected), owned by the active window, with dialogMainService.ts's lock (shared with macOS). Built, not yet run on Windows. | `cargo gc test -p app file_dialog` on the host: `windows_filters_become_semicolon_specs_and_the_first_specific_one_is_selected`, `one_dialog_of_the_same_options_per_window`; [windows] the dialog on the windows runner |
+| M24 Windows | app/src/dialog.rs:5 | in progress | [windows M] native message box through TaskDialogIndirect (dialog/windows.rs), as Electron's message_box_win.cc with `noLink`: buttons in the order dialogs.ts `massageMessageBoxOptions` gives Windows (the caller's, cancel last) with `&` mnemonics, the message as main instruction above a detail, the checkbox as the verification text, owner window modal, Esc and the close button answer cancel. Common Controls 6 comes from GPUI's manifest (`windows-manifest`). Built, not yet run on Windows. | `cargo gc test -p app dialog::tests` on the host: `windows_labels_take_ampersand_mnemonics`, `windows_task_dialog_keeps_the_callers_button_order_with_cancel_last`, `windows_task_dialog_message_is_the_main_instruction_only_with_a_detail`; [windows] the dialog on the windows runner |
| M24 Windows | app/src/webview.rs:11 | open | [windows L] webviews through WebView2 (webview2-com, decision "Windows webview") as child windows of GPUI's HWND, with the host page, resource scheme and message bridge `webview.rs` shares with macOS and Linux: panels and views, editor insets, notebook outputs, extension details, release notes. The WebView2 runtime ships with Windows 10 and 11. | `FIXTURE=webview-tests` smoke on the windows runner; `cargo gc test -p app webview` there |
| M24 Windows | exthost/src/lib.rs:31 | open | [windows L] extension host connection over a named pipe (`\\.\pipe\vscode-ipc-<uuid>-sock`, ipc.net.ts `createRandomIPCHandle` on Windows) instead of a Unix socket; Bun's `net.connect` takes the pipe path. | `cargo gc test -p exthost` on the windows runner: the handshake test |
| M24 Windows | app/src/launch.rs:5 | open | [windows M] single instance and second-instance arguments over a named pipe (main.ts `mainIPCHandle` on Windows). | `cargo gc test -p app launch` on the windows runner |
diff --git a/port/notes.md b/port/notes.md
index ed31af09d2b..b930cee3878 100644
--- a/port/notes.md
+++ b/port/notes.md
@@ -1011,6 +1011,7 @@ What to do (milestone 21, in order):
- Layout: as milestone 23, with `cfg(target_os = "windows")` beside the macOS and Linux code and a `windows.rs` beside `macos.rs` and `linux.rs` where the split is large; Windows gaps are the "M24 Windows" rows of the Work table in port/ledger.md, sized `[windows S|M|L]`.
- Cross build: the Studio has the `x86_64-pc-windows-msvc` and `aarch64-pc-windows-msvc` Rust targets, cargo-xwin (it downloads the MSVC CRT and Windows SDK headers on first use) and Homebrew `llvm` and `lld` (clang-cl, lld-link). It checks that the Windows build compiles; tests that need Windows run on the `windows.yml` runners.
+- Dialogs: file dialogs (`file_dialog/windows.rs`) follow Electron 43's file_dialog_win.cc (`ApplySettings`, `ConvertFilters`, the open and save `FOS_` options), message boxes (`dialog/windows.rs`) its message_box_win.cc with `noLink`, so custom buttons, not command links. Both use the `windows` crate at GPUI's version (0.61) for the COM interfaces. Difference: Electron runs both on its dialog thread (`dialog_thread::Run`); here they run on GPUI's main thread in the dialog's modal loop, as GPUI's own path prompts do, and the GPUI windows keep painting through it. TaskDialogIndirect needs Common Controls 6, which GPUI's embedded manifest (`windows-manifest` feature) declares; a second `/MANIFEST:EMBED` fails the link with a duplicate resource. The pure parts (filter specs, button ids and answers, `&` mnemonics, the main instruction) are host tests in file_dialog.rs and dialog.rs.
## Accepted platform differences