use std::{ cell::{Cell, RefCell}, ffi::{OsStr, OsString}, os::windows::ffi::{OsStrExt as _, OsStringExt as _}, path::{Path, PathBuf}, rc::{Rc, Weak}, sync::{ Arc, atomic::{AtomicBool, Ordering}, }, }; use anyhow::{Context as _, Result, anyhow}; use futures::channel::oneshot::Receiver; use gpui_util::{ResultExt, get_powershell, new_std_command}; use itertools::Itertools; use parking_lot::RwLock; use smallvec::SmallVec; use windows::{ UI::ViewManagement::UISettings, Win32::{ Foundation::*, Graphics::{Direct3D11::ID3D11Device, Gdi::*}, Security::Credentials::*, System::{ Com::*, LibraryLoader::*, Ole::*, Power::*, SystemInformation::*, SystemServices::POWER_REQUEST_CONTEXT_VERSION, Threading::{POWER_REQUEST_CONTEXT_SIMPLE_STRING, REASON_CONTEXT, REASON_CONTEXT_0}, }, UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*}, }, core::*, }; use crate::*; use gpui::*; struct TrackedWindow { handle: SafeHwnd, frame_signal: Arc, } impl TrackedWindow { fn as_raw(&self) -> HWND { self.handle.as_raw() } } pub struct WindowsPlatform { inner: Rc, raw_window_handles: Arc>>, /// The windowing mode to start in, applied when `run` starts. Windowed when unset. initial_windowing: RefCell>, /// Set to stop the current `VSyncProvider` thread, which runs while windowed. vsync_stop: RefCell>>, // The below members will never change throughout the entire lifecycle of the app. /// Created with `headless()`: never windowed, and without a real text system. headless: bool, icon: HICON, background_executor: BackgroundExecutor, foreground_executor: ForegroundExecutor, text_system: Arc, direct_write_text_system: Option>, drop_target_helper: Option, /// Flag to instruct the `VSyncProvider` thread to invalidate the directx devices /// as resizing them has failed, causing us to have lost at least the render target. invalidate_devices: Arc, handle: HWND, suspend_resume_notification: RefCell>, disable_direct_composition: bool, has_package_identity: bool, app_identity: RefCell>, system_notifications: RefCell, } struct WindowsPlatformInner { state: WindowsPlatformState, raw_window_handles: std::sync::Weak>>, // The below members will never change throughout the entire lifecycle of the app. validation_number: usize, main_receiver: PriorityQueueReceiver, dispatcher: Arc, } pub(crate) struct WindowsPlatformState { callbacks: PlatformCallbacks, menus: RefCell>, jump_list: RefCell, // NOTE: standard cursor handles don't need to close. pub(crate) current_cursor: Cell>, /// Shared with each window so `WM_SETCURSOR` can read it directly. pub(crate) cursor_visible: Arc, /// Shared with each window to coordinate draws across windows on the UI /// thread; see [`DrawCoordinator`]. pub(crate) draw_coordinator: Rc, directx_devices: RefCell>, } #[derive(Default)] struct PlatformCallbacks { open_urls: Cell)>>>, quit: Cell bool>>>, reopen: Cell>>, app_menu_action: Cell>>, will_open_app_menu: Cell>>, validate_app_menu_command: Cell bool>>>, keyboard_layout_change: Cell>>, system_sleep: Cell>>, system_wake: Cell>>, } impl WindowsPlatformState { fn new(directx_devices: Option) -> Self { let callbacks = PlatformCallbacks::default(); let jump_list = JumpList::new(); let current_cursor = load_cursor(CursorStyle::Arrow); Self { callbacks, jump_list: RefCell::new(jump_list), current_cursor: Cell::new(current_cursor), cursor_visible: Arc::new(AtomicBool::new(true)), draw_coordinator: Rc::new(DrawCoordinator::new()), directx_devices: RefCell::new(directx_devices), menus: RefCell::new(Vec::new()), } } } struct PowerRequest { handle: HANDLE, // `PowerCreateRequest` retains a pointer into the reason string for the // lifetime of the handle, so the UTF-16 buffer must outlive the request. _reason: Vec, } unsafe impl Send for PowerRequest {} impl PowerRequest { fn prevent_idle_sleep(reason: &str) -> Result { let mut reason = reason.encode_utf16().chain([0]).collect::>(); let context = REASON_CONTEXT { Version: POWER_REQUEST_CONTEXT_VERSION, Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING, Reason: REASON_CONTEXT_0 { SimpleReasonString: PWSTR(reason.as_mut_ptr()), }, }; let handle = unsafe { PowerCreateRequest(&context) } .context("Failed to create a Windows power request")?; if let Err(error) = unsafe { PowerSetRequest(handle, PowerRequestSystemRequired) } { unsafe { CloseHandle(handle) } .context("Failed to close the Windows power request") .log_err(); return Err(error).context("Failed to set the Windows power request"); } Ok(Self { handle, _reason: reason, }) } } impl Drop for PowerRequest { fn drop(&mut self) { unsafe { PowerClearRequest(self.handle, PowerRequestSystemRequired) } .context("Failed to clear the Windows power request") .log_err(); unsafe { CloseHandle(self.handle) } .context("Failed to close the Windows power request") .log_err(); } } impl WindowsPlatform { pub fn new(headless: bool) -> Result { unsafe { OleInitialize(None).context("unable to initialize Windows OLE")?; } // A platform that can become windowed needs the real text system from the start: the app // keeps the one it's created with. It gets DirectX devices when it becomes windowed. let (text_system, direct_write_text_system) = if !headless { let dw_text_system = Arc::new( DirectWriteTextSystem::new(None).context("Error creating DirectWriteTextSystem")?, ); ( dw_text_system.clone() as Arc, Some(dw_text_system), ) } else { ( Arc::new(gpui::NoopTextSystem::new()) as Arc, None, ) }; let (main_sender, main_receiver) = PriorityQueueReceiver::new(); let validation_number = if usize::BITS == 64 { rand::random::() as usize } else { rand::random::() as usize }; let raw_window_handles = Arc::new(RwLock::new(SmallVec::new())); register_platform_window_class(); let mut context = PlatformWindowCreateContext { inner: None, raw_window_handles: Arc::downgrade(&raw_window_handles), validation_number, main_sender: Some(main_sender), main_receiver: Some(main_receiver), directx_devices: None, dispatcher: None, }; let result = unsafe { CreateWindowExW( WINDOW_EX_STYLE(0), PLATFORM_WINDOW_CLASS_NAME, None, WINDOW_STYLE(0), 0, 0, 0, 0, Some(HWND_MESSAGE), None, None, Some(&raw const context as *const _), ) }; let inner = context .inner .take() .context("CreateWindowExW did not run correctly")??; let dispatcher = context .dispatcher .take() .context("CreateWindowExW did not run correctly")?; let handle = result?; let disable_direct_composition = std::env::var(DISABLE_DIRECT_COMPOSITION) .is_ok_and(|value| value == "true" || value == "1"); let background_executor = BackgroundExecutor::new(dispatcher.clone()); let foreground_executor = ForegroundExecutor::new(dispatcher); let drop_target_helper: Option = if !headless { Some(unsafe { CoCreateInstance(&CLSID_DragDropHelper, None, CLSCTX_INPROC_SERVER) .context("Error creating drop target helper.")? }) } else { None }; let icon = if !headless { load_icon().unwrap_or_default() } else { HICON::default() }; Ok(Self { inner, handle, raw_window_handles, initial_windowing: RefCell::new(None), vsync_stop: RefCell::new(None), headless, icon, background_executor, foreground_executor, text_system, direct_write_text_system, suspend_resume_notification: RefCell::new(None), disable_direct_composition, has_package_identity: has_package_identity(), drop_target_helper, invalidate_devices: Arc::new(AtomicBool::new(false)), app_identity: RefCell::new(None), system_notifications: RefCell::new(SystemNotificationState::new()), }) } pub(crate) fn window_from_hwnd(&self, hwnd: HWND) -> Option> { self.raw_window_handles .read() .iter() .find(|entry| entry.as_raw() == hwnd) .and_then(|hwnd| window_from_hwnd(hwnd.as_raw())) } #[inline] fn post_message(&self, message: u32, wparam: WPARAM, lparam: LPARAM) { self.raw_window_handles .read() .iter() .for_each(|handle| unsafe { PostMessageW(Some(handle.as_raw()), message, wparam, lparam).log_err(); }); } fn generate_creation_info(&self) -> WindowCreationInfo { WindowCreationInfo { icon: self.icon, executor: self.foreground_executor.clone(), current_cursor: self.inner.state.current_cursor.get(), cursor_visible: self.inner.state.cursor_visible.clone(), drop_target_helper: self.drop_target_helper.clone().unwrap(), validation_number: self.inner.validation_number, main_receiver: self.inner.main_receiver.clone(), platform_window_handle: self.handle, disable_direct_composition: self.disable_direct_composition, directx_devices: self.inner.state.directx_devices.borrow().clone().unwrap(), invalidate_devices: self.invalidate_devices.clone(), draw_coordinator: self.inner.state.draw_coordinator.clone(), } } fn set_dock_menus(&self, menus: Vec) { let mut actions = Vec::new(); menus.into_iter().for_each(|menu| { if let Some(dock_menu) = DockMenuItem::new(menu).log_err() { actions.push(dock_menu); } }); self.inner.state.jump_list.borrow_mut().dock_menus = actions; let borrow = self.inner.state.jump_list.borrow(); let dock_menus = borrow .dock_menus .iter() .map(|menu| (menu.name.clone(), menu.description.clone())) .collect::>(); let recent_workspaces = borrow.recent_workspaces.clone(); self.background_executor .spawn(async move { update_jump_list(&recent_workspaces, &dock_menus).log_err(); }) .detach(); } fn update_jump_list( &self, menus: Vec, entries: Vec>, ) -> Task>> { let mut actions = Vec::new(); menus.into_iter().for_each(|menu| { if let Some(dock_menu) = DockMenuItem::new(menu).log_err() { actions.push(dock_menu); } }); let mut jump_list = self.inner.state.jump_list.borrow_mut(); jump_list.dock_menus = actions; jump_list.recent_workspaces = entries.into(); let dock_menus = jump_list .dock_menus .iter() .map(|menu| (menu.name.clone(), menu.description.clone())) .collect::>(); let recent_workspaces = jump_list.recent_workspaces.clone(); self.background_executor.spawn(async move { update_jump_list(&recent_workspaces, &dock_menus) .log_err() .unwrap_or_default() }) } fn find_current_active_window(&self) -> Option { let active_window_hwnd = unsafe { GetActiveWindow() }; if active_window_hwnd.is_invalid() { return None; } self.raw_window_handles .read() .iter() .find(|hwnd| hwnd.as_raw() == active_window_hwnd) .map(|hwnd| hwnd.as_raw()) } fn is_windowed(&self) -> bool { self.inner.state.directx_devices.borrow().is_some() } /// Connects in the initial windowing mode, before the app finishes launching. /// /// # Panics /// /// Panics if DirectX can't be initialized, since the app can't start. Starts headless if this /// process can't show windows, for example when started over SSH. fn connect_initially(&self) { let request = self .initial_windowing .borrow_mut() .take() .unwrap_or_else(|| WindowingRequest::Windowed(GraphicalEnvironment::detect())); let WindowingRequest::Windowed(environment) = request else { return; }; if let Err(error) = check_can_show_windows(&environment) { log::info!("starting headless: {error:#}"); return; } self.attach_gpu() .unwrap_or_else(|error| panic!("failed to initialize DirectX: {error:#}")); } /// Creates the DirectX devices that windows draw with, and starts vsync. fn attach_gpu(&self) -> Result<()> { let devices = DirectXDevices::new().context("Creating DirectX devices")?; if let Some(text_system) = &self.direct_write_text_system { text_system.handle_gpu_lost(&devices)?; } *self.inner.state.directx_devices.borrow_mut() = Some(devices); self.begin_vsync_thread(); Ok(()) } /// Stops vsync and releases the DirectX devices. No window may be open. fn detach_gpu(&self) { if let Some(stop) = self.vsync_stop.borrow_mut().take() { // Not joined: the thread can be sending this thread a message. It exits after its // next vsync, and drops its reference to the devices then. stop.store(true, Ordering::Release); } if let Some(text_system) = &self.direct_write_text_system { text_system.release_gpu(); } self.inner.state.directx_devices.borrow_mut().take(); } fn begin_vsync_thread(&self) { let Some(directx_devices) = self.inner.state.directx_devices.borrow().clone() else { return; }; let Some(direct_write_text_system) = &self.direct_write_text_system else { return; }; let stop = Arc::new(AtomicBool::new(false)); *self.vsync_stop.borrow_mut() = Some(stop.clone()); let mut directx_device = directx_devices; let platform_window: SafeHwnd = self.handle.into(); let validation_number = self.inner.validation_number; let all_windows = Arc::downgrade(&self.raw_window_handles); let text_system = Arc::downgrade(direct_write_text_system); let invalidate_devices = self.invalidate_devices.clone(); std::thread::Builder::new() .name("VSyncProvider".to_owned()) .spawn(move || { let vsync_provider = VSyncProvider::new(); loop { let signal_source = vsync_provider.wait_for_vsync(); let signal_at = PlatformFrameSignal::capture(scheduler::Instant::now); if stop.load(Ordering::Acquire) { break; } if check_device_lost(&directx_device.device) || invalidate_devices.fetch_and(false, Ordering::Acquire) { if let Err(err) = handle_gpu_device_lost( &mut directx_device, platform_window.as_raw(), validation_number, &all_windows, &text_system, ) { panic!("Device lost: {err}"); } } let Some(all_windows) = all_windows.upgrade() else { break; }; for hwnd in all_windows.read().iter() { unsafe { if let Some(signal_at) = signal_at { if IsWindowVisible(hwnd.as_raw()).as_bool() && !IsIconic(hwnd.as_raw()).as_bool() { hwnd.frame_signal.record(signal_at, signal_source); } else { // Hidden windows may not consume WM_PAINT until shown again. hwnd.frame_signal.take(); } } RedrawWindow(Some(hwnd.as_raw()), None, None, RDW_INVALIDATE) .ok() .log_err(); } } } }) .unwrap(); } } fn translate_accelerator(msg: &MSG) -> Option<()> { if msg.message != WM_KEYDOWN && msg.message != WM_SYSKEYDOWN { return None; } let result = unsafe { SendMessageW( msg.hwnd, WM_GPUI_KEYDOWN, Some(msg.wParam), Some(msg.lParam), ) }; (result.0 == 0).then_some(()) } fn encode_restart_arguments(arguments: &[OsString]) -> OsString { // `Start-Process` accepts a single native command line, so quote each argument according to // the Windows argv parsing rules before passing the complete string through the environment. let mut encoded = Vec::new(); for (index, argument) in arguments.iter().enumerate() { if index > 0 { encoded.push(b' ' as u16); } encoded.push(b'"' as u16); let mut backslash_count = 0; for code_unit in argument.encode_wide() { if code_unit == b'\\' as u16 { backslash_count += 1; } else { if code_unit == b'"' as u16 { encoded.extend(std::iter::repeat_n(b'\\' as u16, backslash_count * 2 + 1)); } else { encoded.extend(std::iter::repeat_n(b'\\' as u16, backslash_count)); } backslash_count = 0; encoded.push(code_unit); } } encoded.extend(std::iter::repeat_n(b'\\' as u16, backslash_count * 2)); encoded.push(b'"' as u16); } OsString::from_wide(&encoded) } impl Platform for WindowsPlatform { fn background_executor(&self) -> BackgroundExecutor { self.background_executor.clone() } fn foreground_executor(&self) -> ForegroundExecutor { self.foreground_executor.clone() } fn text_system(&self) -> Arc { self.text_system.clone() } fn keyboard_layout(&self) -> Box { Box::new( WindowsKeyboardLayout::new() .log_err() .unwrap_or(WindowsKeyboardLayout::unknown()), ) } fn keyboard_mapper(&self) -> Rc { Rc::new(WindowsKeyboardMapper::new()) } fn on_keyboard_layout_change(&self, callback: Box) { self.inner .state .callbacks .keyboard_layout_change .set(Some(callback)); } fn on_thermal_state_change(&self, _callback: Box) {} fn thermal_state(&self) -> ThermalState { ThermalState::Nominal } fn prevent_idle_sleep(&self, reason: &str) -> Task> { Task::ready( PowerRequest::prevent_idle_sleep(reason) .map(|request| ActivityGuard::new(move || drop(request))), ) } fn run(&self, on_finish_launching: Box) { if !self.headless { self.connect_initially(); } on_finish_launching(); let mut msg = MSG::default(); unsafe { while GetMessageW(&mut msg, None, 0, 0).as_bool() { if translate_accelerator(&msg).is_none() { _ = TranslateMessage(&msg); DispatchMessageW(&msg); } } } self.inner.with_callback( |callbacks| &callbacks.quit, |callback| { callback(); }, ); } fn quit(&self) { self.foreground_executor() .spawn(async { unsafe { PostQuitMessage(0) } }) .detach(); } fn set_initial_windowing(&self, request: WindowingRequest) { *self.initial_windowing.borrow_mut() = Some(request); } fn request_windowing(&self, request: WindowingRequest) -> Task> { if self.headless { return Task::ready(Err(anyhow!( "a platform created headless can't switch windowing modes" ))); } let windowed = self.is_windowed(); Task::ready(match request { WindowingRequest::Headless if !windowed => Err(anyhow!("already headless")), WindowingRequest::Headless => { self.detach_gpu(); Ok(()) } WindowingRequest::Windowed(_) if windowed => Err(anyhow!("already windowed")), WindowingRequest::Windowed(environment) => { check_can_show_windows(&environment).and_then(|()| self.attach_gpu()) } }) } fn graphical_environment(&self) -> Option { self.is_windowed().then(GraphicalEnvironment::detect) } fn restart(&self, binary_path: Option, arguments: Vec) { let pid = std::process::id(); let Some(app_path) = binary_path.or(self.app_path().log_err()) else { return; }; let script = r#" $pidToWaitFor = $env:ZED_RESTART_PID $exePath = $env:ZED_RESTART_EXECUTABLE $argumentList = $env:ZED_RESTART_ARGUMENTS [Environment]::SetEnvironmentVariable("ZED_RESTART_PID", $null) [Environment]::SetEnvironmentVariable("ZED_RESTART_EXECUTABLE", $null) [Environment]::SetEnvironmentVariable("ZED_RESTART_ARGUMENTS", $null) while ($true) { $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue if (-not $process) { if ([string]::IsNullOrEmpty($argumentList)) { Start-Process -FilePath $exePath } else { Start-Process -FilePath $exePath -ArgumentList $argumentList } break } Start-Sleep -Seconds 0.1 } "#; // Defer spawning to the foreground executor so it runs after the // current `AppCell` borrow is released. On Windows, `Command::spawn()` // can pump the Win32 message loop (via `CreateProcessW`), which // re-enters message handling possibly resulting in another mutable // borrow of the `AppCell` ending up with a double borrow panic let Some(powershell) = get_powershell() else { log::error!("failed to restart: PowerShell is unavailable"); return; }; self.foreground_executor .spawn(async move { let mut command = new_std_command(powershell); let arguments = encode_restart_arguments(&arguments); command .arg("-command") .arg(script) .env("ZED_RESTART_PID", pid.to_string()) .env("ZED_RESTART_EXECUTABLE", app_path) .env("ZED_RESTART_ARGUMENTS", arguments); #[allow( clippy::disallowed_methods, reason = "We are restarting ourselves, using std command thus is fine" )] let restart_process = command.spawn(); match restart_process { Ok(_) => unsafe { PostQuitMessage(0) }, Err(e) => log::error!("failed to spawn restart script: {:?}", e), } }) .detach(); } fn activate(&self, _ignoring_other_apps: bool) {} fn hide(&self) {} // todo(windows) fn hide_other_apps(&self) { unimplemented!() } // todo(windows) fn unhide_other_apps(&self) { unimplemented!() } fn displays(&self) -> Vec> { WindowsDisplay::displays() } fn primary_display(&self) -> Option> { WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc) } #[cfg(feature = "screen-capture")] fn is_screen_capture_supported(&self) -> bool { true } #[cfg(feature = "screen-capture")] fn screen_capture_sources( &self, ) -> futures::channel::oneshot::Receiver>>> { gpui::scap_screen_capture::scap_screen_sources(&self.foreground_executor) } fn active_window(&self) -> Option { let active_window_hwnd = unsafe { GetActiveWindow() }; self.window_from_hwnd(active_window_hwnd) .map(|inner| inner.handle) } fn open_window( &self, handle: AnyWindowHandle, options: WindowParams, ) -> Result> { if !self.is_windowed() { return Err(anyhow!("cannot open windows while headless")); } let window = WindowsWindow::new(handle, options, self.generate_creation_info())?; let handle = window.get_raw_handle(); self.raw_window_handles.write().push(TrackedWindow { handle: handle.into(), frame_signal: window.state.frame_signal.clone(), }); Ok(Box::new(window)) } fn window_appearance(&self) -> WindowAppearance { system_appearance().log_err().unwrap_or_default() } fn open_url(&self, url: &str) { if url.is_empty() { return; } let url_string = url.to_string(); self.background_executor() .spawn(async move { open_target(&url_string) .with_context(|| format!("Opening url: {}", url_string)) .log_err(); }) .detach(); } fn on_open_urls(&self, callback: Box)>) { self.inner.state.callbacks.open_urls.set(Some(callback)); } fn prompt_for_paths( &self, options: PathPromptOptions, ) -> Receiver>>> { let owner = self .find_current_active_window() .and_then(|hwnd| self.window_from_hwnd(hwnd)) .map(|window| window.dialog_owner.clone()); crate::dialog::show_dialog(owner, &self.foreground_executor, move |window| { file_open_dialog(options, Some(window)) }) } fn prompt_for_new_path( &self, directory: &Path, suggested_name: Option<&str>, ) -> Receiver>> { let directory = directory.to_owned(); let suggested_name = suggested_name.map(|s| s.to_owned()); let owner = self .find_current_active_window() .and_then(|hwnd| self.window_from_hwnd(hwnd)) .map(|window| window.dialog_owner.clone()); crate::dialog::show_dialog(owner, &self.foreground_executor, move |window| { file_save_dialog(directory, suggested_name, Some(window)) }) } fn can_select_mixed_files_and_dirs(&self) -> bool { // The FOS_PICKFOLDERS flag toggles between "only files" and "only folders". false } fn reveal_path(&self, path: &Path) { if path.as_os_str().is_empty() { return; } let path = path.to_path_buf(); self.background_executor() .spawn(async move { open_target_in_explorer(&path) .with_context(|| format!("Revealing path {} in explorer", path.display())) .log_err(); }) .detach(); } fn open_with_system(&self, path: &Path) { if path.as_os_str().is_empty() { return; } let path = path.to_path_buf(); self.background_executor() .spawn(async move { open_target(&path) .with_context(|| format!("Opening {} with system", path.display())) .log_err(); }) .detach(); } fn on_quit(&self, callback: Box bool>) { self.inner.state.callbacks.quit.set(Some(callback)); } fn on_reopen(&self, callback: Box) { self.inner.state.callbacks.reopen.set(Some(callback)); } fn on_system_sleep(&self, callback: Box) { self.inner.state.callbacks.system_sleep.set(Some(callback)); } fn on_system_wake(&self, callback: Box) { self.inner.state.callbacks.system_wake.set(Some(callback)); let mut notification = self.suspend_resume_notification.borrow_mut(); if notification.is_none() { *notification = unsafe { // SAFETY: self.handle is the platform window receiving WM_POWERBROADCAST. RegisterSuspendResumeNotification( HANDLE(self.handle.0), DEVICE_NOTIFY_WINDOW_HANDLE, ) .log_err() }; } } fn set_app_identity(&self, identifier: &str, name: &str) { // If the process has package identity, it's automatally granted an AUMID by the system. if self.has_package_identity { return; } let identifier_utf16 = windows::core::HSTRING::from(identifier); // SAFETY: `identifier_utf16` outlives the call and is null-terminated. if let Err(error) = unsafe { windows::Win32::UI::Shell::SetCurrentProcessExplicitAppUserModelID( windows::core::PCWSTR(identifier_utf16.as_ptr()), ) } { log::warn!("failed to set the process AppUserModelID: {error}"); } *self.app_identity.borrow_mut() = Some((identifier.to_string(), name.to_string())); } fn show_system_notification(&self, notification: gpui::SystemNotification) { let app_identity = self.app_identity.borrow().clone(); self.system_notifications .borrow_mut() .show( self.has_package_identity, app_identity .as_ref() .map(|(identifier, name)| (identifier.as_str(), name.as_str())), notification, ) .log_err(); } fn dismiss_system_notification(&self, tag: &str) { self.system_notifications.borrow_mut().dismiss(tag); } fn on_system_notification_response( &self, callback: Box, ) { self.system_notifications .borrow_mut() .on_response(&self.foreground_executor, callback); } fn set_menus(&self, menus: Vec, _keymap: &Keymap) { *self.inner.state.menus.borrow_mut() = menus.into_iter().map(|menu| menu.owned()).collect(); } fn get_menus(&self) -> Option> { Some(self.inner.state.menus.borrow().clone()) } fn set_dock_menu(&self, menus: Vec, _keymap: &Keymap) { self.set_dock_menus(menus); } fn on_app_menu_action(&self, callback: Box) { self.inner .state .callbacks .app_menu_action .set(Some(callback)); } fn on_will_open_app_menu(&self, callback: Box) { self.inner .state .callbacks .will_open_app_menu .set(Some(callback)); } fn on_validate_app_menu_command(&self, callback: Box bool>) { self.inner .state .callbacks .validate_app_menu_command .set(Some(callback)); } fn app_path(&self) -> Result { Ok(std::env::current_exe()?) } // todo(windows) fn path_for_auxiliary_executable(&self, _name: &str) -> Result { anyhow::bail!("not yet implemented"); } fn set_cursor_style(&self, style: CursorStyle) { let hcursor = load_cursor(style); if self.inner.state.current_cursor.get().map(|c| c.0) != hcursor.map(|c| c.0) { self.post_message( WM_GPUI_CURSOR_STYLE_CHANGED, WPARAM(0), LPARAM(hcursor.map_or(0, |c| c.0 as isize)), ); self.inner.state.current_cursor.set(hcursor); } } fn hide_cursor_until_mouse_moves(&self) { if !self .inner .state .cursor_visible .swap(false, Ordering::Relaxed) { return; } for handle in self.raw_window_handles.read().iter() { let Some(window) = window_from_hwnd(handle.as_raw()) else { continue; }; if window.state.hovered.get() { unsafe { SetCursor(None) }; break; } } } fn is_cursor_visible(&self) -> bool { self.inner.state.cursor_visible.load(Ordering::Relaxed) } fn should_auto_hide_scrollbars(&self) -> bool { should_auto_hide_scrollbars().log_err().unwrap_or(false) } fn write_to_clipboard(&self, item: ClipboardItem) { write_to_clipboard(item); } fn read_from_clipboard(&self) -> Option { read_from_clipboard() } fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task> { // CredWriteW rejects larger blobs with the opaque RPC error // 0x800706F7 "The stub received bad data", so fail with a clear // message instead. if password.len() > CRED_MAX_CREDENTIAL_BLOB_SIZE as usize { return Task::ready(Err(anyhow!( "credential for {url} is {} bytes, which exceeds the Windows Credential Manager limit of {CRED_MAX_CREDENTIAL_BLOB_SIZE} bytes", password.len() ))); } let password = password.to_vec(); let mut username = username.encode_utf16().chain(Some(0)).collect_vec(); let mut target_name = windows_credentials_target_name(url) .encode_utf16() .chain(Some(0)) .collect_vec(); self.background_executor().spawn(async move { let credentials = CREDENTIALW { LastWritten: unsafe { GetSystemTimeAsFileTime() }, Flags: CRED_FLAGS(0), Type: CRED_TYPE_GENERIC, TargetName: PWSTR::from_raw(target_name.as_mut_ptr()), CredentialBlobSize: password.len() as u32, CredentialBlob: password.as_ptr() as *mut _, Persist: CRED_PERSIST_LOCAL_MACHINE, UserName: PWSTR::from_raw(username.as_mut_ptr()), ..CREDENTIALW::default() }; unsafe { CredWriteW(&credentials, 0).map_err(|err| { anyhow!( "Failed to write credentials to Windows Credential Manager: {}", err, ) })?; } Ok(()) }) } fn read_credentials(&self, url: &str) -> Task)>>> { let target_name = windows_credentials_target_name(url) .encode_utf16() .chain(Some(0)) .collect_vec(); self.background_executor().spawn(async move { let mut credentials: *mut CREDENTIALW = std::ptr::null_mut(); let result = unsafe { CredReadW( PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, None, &mut credentials, ) }; if let Err(err) = result { // ERROR_NOT_FOUND means the credential doesn't exist. // Return Ok(None) to match macOS and Linux behavior. if err.code() == ERROR_NOT_FOUND.to_hresult() { return Ok(None); } return Err(err.into()); } if credentials.is_null() { return Ok(None); } // SAFETY: `CredReadW` succeeded, so this points to a valid `CREDENTIALW` until `CredFree` below. let result = unsafe { username_and_password(&*credentials) }; unsafe { CredFree(credentials as *const _ as _) }; result.map(Some) }) } fn delete_credentials(&self, url: &str) -> Task> { let target_name = windows_credentials_target_name(url) .encode_utf16() .chain(Some(0)) .collect_vec(); self.background_executor().spawn(async move { unsafe { CredDeleteW( PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, None, )? }; Ok(()) }) } fn register_url_scheme(&self, _: &str) -> Task> { Task::ready(Err(anyhow!("register_url_scheme unimplemented"))) } fn perform_dock_menu_action(&self, action: usize) { unsafe { PostMessageW( Some(self.handle), WM_GPUI_DOCK_MENU_ACTION, WPARAM(self.inner.validation_number), LPARAM(action as isize), ) .log_err(); } } fn update_jump_list( &self, menus: Vec, entries: Vec>, ) -> Task>> { self.update_jump_list(menus, entries) } } impl WindowsPlatformInner { fn new(context: &mut PlatformWindowCreateContext) -> Result> { let state = WindowsPlatformState::new(context.directx_devices.take()); Ok(Rc::new(Self { state, raw_window_handles: context.raw_window_handles.clone(), dispatcher: context .dispatcher .as_ref() .context("missing dispatcher")? .clone(), validation_number: context.validation_number, main_receiver: context .main_receiver .take() .context("missing main receiver")?, })) } /// Calls `project` to project to the corresponding callback field, removes it from callbacks, calls `f` with the callback and then puts the callback back. fn with_callback( &self, project: impl Fn(&PlatformCallbacks) -> &Cell>, f: impl FnOnce(&mut T), ) { let callback = project(&self.state.callbacks).take(); if let Some(mut callback) = callback { f(&mut callback); project(&self.state.callbacks).set(Some(callback)); } } fn handle_msg( self: &Rc, handle: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM, ) -> LRESULT { let handled = match msg { WM_GPUI_CLOSE_ONE_WINDOW | WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD | WM_GPUI_DOCK_MENU_ACTION | WM_GPUI_KEYBOARD_LAYOUT_CHANGED | WM_GPUI_GPU_DEVICE_LOST | WM_GPUI_END_SESSION => self.handle_gpui_events(msg, wparam, lparam), WM_POWERBROADCAST => self.handle_power_broadcast(wparam), _ => None, }; if let Some(result) = handled { LRESULT(result) } else { unsafe { DefWindowProcW(handle, msg, wparam, lparam) } } } fn handle_gpui_events(&self, message: u32, wparam: WPARAM, lparam: LPARAM) -> Option { if wparam.0 != self.validation_number { log::error!("Wrong validation number while processing message: {message}"); return None; } match message { WM_GPUI_CLOSE_ONE_WINDOW => { self.close_one_window(HWND(lparam.0 as _)); Some(0) } WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD => self.run_foreground_task(), WM_GPUI_DOCK_MENU_ACTION => self.handle_dock_action_event(lparam.0 as _), WM_GPUI_KEYBOARD_LAYOUT_CHANGED => self.handle_keyboard_layout_change(), WM_GPUI_GPU_DEVICE_LOST => self.handle_device_lost(lparam), WM_GPUI_END_SESSION => self.handle_end_session(), _ => unreachable!(), } } fn handle_end_session(&self) -> Option { let mut shutdown_completed = false; self.with_callback( |callbacks| &callbacks.quit, |callback| shutdown_completed = callback(), ); log::logger().flush(); if shutdown_completed { std::process::exit(0); } // Shutdown couldn't run synchronously, since the AppCell is already borrowed. // Windows may terminate the application as soon as we return from this handler, but if we post a WM_QUIT message now, // we may get to gracefully shut down the app before we're terminated by the OS. unsafe { PostQuitMessage(0) }; Some(0) } fn close_one_window(&self, target_window: HWND) -> bool { let Some(all_windows) = self.raw_window_handles.upgrade() else { log::error!("Failed to upgrade raw window handles"); return false; }; let mut lock = all_windows.write(); let index = lock .iter() .position(|handle| handle.as_raw() == target_window) .unwrap(); lock.remove(index); lock.is_empty() } #[inline] fn run_foreground_task(&self) -> Option { const MAIN_TASK_TIMEOUT: u128 = 10; let start = std::time::Instant::now(); 'tasks: loop { 'timeout_loop: loop { if start.elapsed().as_millis() >= MAIN_TASK_TIMEOUT { log::debug!("foreground task timeout reached"); // we spent our budget on gpui tasks, we likely have a lot of work queued so drain system events first to stay responsive // then quit out of foreground work to allow us to process other gpui events first before returning back to foreground task work // if we don't we might not for example process window quit events let mut msg = MSG::default(); let process_message = |msg: &_| { if translate_accelerator(msg).is_none() { _ = unsafe { TranslateMessage(msg) }; unsafe { DispatchMessageW(msg) }; } }; let peek_msg = |msg: &mut _, msg_kind| unsafe { PeekMessageW(msg, None, 0, 0, PM_REMOVE | msg_kind).as_bool() }; // We need to process a paint message here as otherwise we will re-enter `run_foreground_task` before painting if we have work remaining. // The reason for this is that windows prefers custom application message processing over system messages. if peek_msg(&mut msg, PM_QS_PAINT) { process_message(&msg); } while peek_msg(&mut msg, PM_QS_INPUT) { process_message(&msg); } // Allow the main loop to process other gpui events before going back into `run_foreground_task` unsafe { if let Err(_) = PostMessageW( Some(self.dispatcher.platform_window_handle.as_raw()), WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD, WPARAM(self.validation_number), LPARAM(0), ) { self.dispatcher.wake_posted.store(false, Ordering::Release); }; } break 'tasks; } let mut main_receiver = self.main_receiver.clone(); match main_receiver.try_pop() { Ok(Some(runnable)) => WindowsDispatcher::execute_runnable(runnable), _ => break 'timeout_loop, } } // Someone could enqueue a Runnable here. The flag is still true, so they will not PostMessage. // We need to check for those Runnables after we clear the flag. self.dispatcher.wake_posted.store(false, Ordering::Release); let mut main_receiver = self.main_receiver.clone(); match main_receiver.try_pop() { Ok(Some(runnable)) => { self.dispatcher.wake_posted.store(true, Ordering::Release); WindowsDispatcher::execute_runnable(runnable); } _ => break 'tasks, } } Some(0) } fn handle_dock_action_event(&self, action_idx: usize) -> Option { let Some(action) = self .state .jump_list .borrow() .dock_menus .get(action_idx) .map(|dock_menu| dock_menu.action.boxed_clone()) else { log::error!("Dock menu for index {action_idx} not found"); return Some(1); }; self.with_callback( |callbacks| &callbacks.app_menu_action, |callback| callback(&*action), ); Some(0) } fn handle_keyboard_layout_change(&self) -> Option { self.with_callback( |callbacks| &callbacks.keyboard_layout_change, |callback| callback(), ); Some(0) } fn handle_power_broadcast(&self, wparam: WPARAM) -> Option { match wparam.0 as u32 { PBT_APMSUSPEND => { self.with_callback(|callbacks| &callbacks.system_sleep, |callback| callback()); } PBT_APMRESUMEAUTOMATIC => { self.with_callback(|callbacks| &callbacks.system_wake, |callback| callback()); } _ => {} } Some(1) } fn handle_device_lost(&self, lparam: LPARAM) -> Option { let directx_devices = lparam.0 as *const DirectXDevices; let directx_devices = unsafe { &*directx_devices }; let mut current = self.state.directx_devices.borrow_mut(); // The platform may have switched to headless while the device was being recovered. if current.is_some() { *current = Some(directx_devices.clone()); } Some(0) } } impl Drop for WindowsPlatform { fn drop(&mut self) { if let Some(stop) = self.vsync_stop.borrow_mut().take() { stop.store(true, Ordering::Release); } unsafe { if let Some(notification) = self.suspend_resume_notification.borrow_mut().take() { // SAFETY: notification was returned by RegisterSuspendResumeNotification. UnregisterSuspendResumeNotification(notification).log_err(); } DestroyWindow(self.handle) .context("Destroying platform window") .log_err(); OleUninitialize(); } } } pub(crate) struct WindowCreationInfo { pub(crate) icon: HICON, pub(crate) executor: ForegroundExecutor, pub(crate) current_cursor: Option, pub(crate) cursor_visible: Arc, pub(crate) drop_target_helper: IDropTargetHelper, pub(crate) validation_number: usize, pub(crate) main_receiver: PriorityQueueReceiver, pub(crate) platform_window_handle: HWND, pub(crate) disable_direct_composition: bool, pub(crate) directx_devices: DirectXDevices, /// Flag to instruct the `VSyncProvider` thread to invalidate the directx devices /// as resizing them has failed, causing us to have lost at least the render target. pub(crate) invalidate_devices: Arc, /// Shared with [`WindowsPlatformState::draw_coordinator`] and every other window. pub(crate) draw_coordinator: Rc, } struct PlatformWindowCreateContext { inner: Option>>, raw_window_handles: std::sync::Weak>>, validation_number: usize, main_sender: Option>, main_receiver: Option>, directx_devices: Option, dispatcher: Option>, } fn has_package_identity() -> bool { let mut package_full_name_length = 0; let result = unsafe { windows::Win32::Storage::Packaging::Appx::GetCurrentPackageFullName( &mut package_full_name_length, None, ) }; if result == ERROR_INSUFFICIENT_BUFFER { true } else if result == APPMODEL_ERROR_NO_PACKAGE { false } else { log::warn!("failed to determine whether the process has package identity: {result:?}"); false } } fn open_target(target: impl AsRef) -> Result<()> { let target = target.as_ref(); let ret = unsafe { ShellExecuteW( None, windows::core::w!("open"), &HSTRING::from(target), None, None, SW_SHOWDEFAULT, ) }; if ret.0 as isize <= 32 { Err(anyhow::anyhow!( "Unable to open target: {}", std::io::Error::last_os_error() )) } else { Ok(()) } } fn open_target_in_explorer(target: &Path) -> Result<()> { let dir = target.parent().context("No parent folder found")?; let desktop = unsafe { SHGetDesktopFolder()? }; let mut dir_item = std::ptr::null_mut(); unsafe { desktop.ParseDisplayName( HWND::default(), None, &HSTRING::from(dir), None, &mut dir_item, std::ptr::null_mut(), )?; } let mut file_item = std::ptr::null_mut(); unsafe { desktop.ParseDisplayName( HWND::default(), None, &HSTRING::from(target), None, &mut file_item, std::ptr::null_mut(), )?; } let highlight = [file_item as *const _]; unsafe { SHOpenFolderAndSelectItems(dir_item as _, Some(&highlight), 0) }.or_else(|err| { if err.code().0 == ERROR_FILE_NOT_FOUND.0 as i32 { // On some systems, the above call mysteriously fails with "file not // found" even though the file is there. In these cases, ShellExecute() // seems to work as a fallback (although it won't select the file). open_target(dir).context("Opening target parent folder") } else { Err(anyhow::anyhow!("Can not open target path: {}", err)) } }) } fn file_open_dialog( options: PathPromptOptions, window: Option, ) -> Result>> { let folder_dialog: IFileOpenDialog = unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? }; let mut dialog_options = FOS_FILEMUSTEXIST; if options.multiple { dialog_options |= FOS_ALLOWMULTISELECT; } if options.directories { dialog_options |= FOS_PICKFOLDERS; } unsafe { folder_dialog.SetOptions(dialog_options)?; if let Some(prompt) = options.prompt { let prompt: &str = &prompt; folder_dialog.SetOkButtonLabel(&HSTRING::from(prompt))?; } if let Err(error) = folder_dialog.Show(window) { if error.code() == HRESULT::from_win32(ERROR_CANCELLED.0) { return Ok(None); } return Err(error.into()); } } let results = unsafe { folder_dialog.GetResults()? }; let file_count = unsafe { results.GetCount()? }; if file_count == 0 { return Ok(None); } let mut paths = Vec::with_capacity(file_count as usize); for i in 0..file_count { let item = unsafe { results.GetItemAt(i)? }; let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? }; paths.push(PathBuf::from(path)); } Ok(Some(paths)) } fn file_save_dialog( directory: PathBuf, suggested_name: Option, window: Option, ) -> Result> { let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? }; if !directory.to_string_lossy().is_empty() && let Some(full_path) = directory .canonicalize() .context("failed to canonicalize directory") .log_err() { let full_path = dunce::simplified(&full_path); let full_path_string = full_path.display().to_string(); let path_item: IShellItem = unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_string), None)? }; unsafe { dialog .SetFolder(&path_item) .context("failed to set dialog folder") .log_err() }; } if let Some(suggested_name) = suggested_name { unsafe { dialog .SetFileName(&HSTRING::from(suggested_name)) .context("failed to set file name") .log_err() }; } unsafe { dialog.SetFileTypes(&[Common::COMDLG_FILTERSPEC { pszName: windows::core::w!("All files"), pszSpec: windows::core::w!("*.*"), }])?; if let Err(error) = dialog.Show(window) { if error.code() == HRESULT::from_win32(ERROR_CANCELLED.0) { return Ok(None); } return Err(error.into()); } } let shell_item = unsafe { dialog.GetResult()? }; let file_path_string = unsafe { let pwstr = shell_item.GetDisplayName(SIGDN_FILESYSPATH)?; let string = pwstr.to_string()?; CoTaskMemFree(Some(pwstr.0 as _)); string }; Ok(Some(PathBuf::from(file_path_string))) } fn load_icon() -> Result { let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? }; let handle = unsafe { LoadImageW( Some(module.into()), windows::core::PCWSTR(1 as _), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_SHARED, ) .context("unable to load icon file")? }; Ok(HICON(handle.0)) } #[inline] fn should_auto_hide_scrollbars() -> Result { let ui_settings = UISettings::new()?; Ok(ui_settings.AutoHideScrollBars()?) } fn check_device_lost(device: &ID3D11Device) -> bool { let device_state = unsafe { device.GetDeviceRemovedReason() }; match device_state { Ok(_) => false, Err(err) => { log::error!("DirectX device lost detected: {:?}", err); true } } } /// Checks that this process can show windows in the session `environment` names. fn check_can_show_windows(environment: &GraphicalEnvironment) -> Result<()> { let current = GraphicalEnvironment::detect().session_id; if let (Some(requested), Some(current)) = (environment.session_id, current) && requested != current { return Err(anyhow!( "windows can only be shown in this process's session ({current}), not session \ {requested}" )); } if !is_window_station_visible() { return Err(anyhow!( "this process's window station is not interactive, so it can't show windows" )); } Ok(()) } /// Whether this process's window station has a visible desktop. A service's, or an SSH login's, /// doesn't. fn is_window_station_visible() -> bool { use windows::Win32::System::StationsAndDesktops::{ GetProcessWindowStation, GetUserObjectInformationW, UOI_FLAGS, USEROBJECTFLAGS, }; let Ok(station) = (unsafe { GetProcessWindowStation() }) else { return false; }; let mut flags = USEROBJECTFLAGS::default(); // SAFETY: `flags` is valid for writes of the size passed. let result = unsafe { GetUserObjectInformationW( HANDLE(station.0), UOI_FLAGS, Some(&mut flags as *mut USEROBJECTFLAGS as *mut std::ffi::c_void), std::mem::size_of::() as u32, None, ) }; result.is_ok() && flags.dwFlags & WSF_VISIBLE as u32 != 0 } fn handle_gpu_device_lost( directx_devices: &mut DirectXDevices, platform_window: HWND, validation_number: usize, all_windows: &std::sync::Weak>>, text_system: &std::sync::Weak, ) -> Result<()> { // Here we wait a bit to ensure the system has time to recover from the device lost state. // If we don't wait, the final drawing result will be blank. std::thread::sleep(std::time::Duration::from_millis(350)); *directx_devices = try_to_recover_from_device_lost(|| { DirectXDevices::new().context("Failed to recreate new DirectX devices after device lost") })?; log::info!("DirectX devices successfully recreated."); let lparam = LPARAM(directx_devices as *const _ as _); unsafe { SendMessageW( platform_window, WM_GPUI_GPU_DEVICE_LOST, Some(WPARAM(validation_number)), Some(lparam), ); } if let Some(text_system) = text_system.upgrade() { text_system.handle_gpu_lost(&directx_devices)?; } if let Some(all_windows) = all_windows.upgrade() { for window in all_windows.read().iter() { unsafe { SendMessageW( window.as_raw(), WM_GPUI_GPU_DEVICE_LOST, Some(WPARAM(validation_number)), Some(lparam), ); } } std::thread::sleep(std::time::Duration::from_millis(200)); for window in all_windows.read().iter() { unsafe { SendMessageW( window.as_raw(), WM_GPUI_FORCE_UPDATE_WINDOW, Some(WPARAM(validation_number)), None, ); } } } Ok(()) } const PLATFORM_WINDOW_CLASS_NAME: PCWSTR = w!("Zed::PlatformWindow"); fn register_platform_window_class() { let wc = WNDCLASSW { lpfnWndProc: Some(window_procedure), lpszClassName: PCWSTR(PLATFORM_WINDOW_CLASS_NAME.as_ptr()), ..Default::default() }; unsafe { RegisterClassW(&wc) }; } unsafe extern "system" fn window_procedure( hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM, ) -> LRESULT { if msg == WM_NCCREATE { let params = unsafe { &*(lparam.0 as *const CREATESTRUCTW) }; let creation_context = params.lpCreateParams as *mut PlatformWindowCreateContext; let creation_context = unsafe { &mut *creation_context }; let Some(main_sender) = creation_context.main_sender.take() else { creation_context.inner = Some(Err(anyhow!("missing main sender"))); return LRESULT(0); }; creation_context.dispatcher = Some(Arc::new(WindowsDispatcher::new( main_sender, hwnd, creation_context.validation_number, ))); return match WindowsPlatformInner::new(creation_context) { Ok(inner) => { let weak = Box::new(Rc::downgrade(&inner)); unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) }; creation_context.inner = Some(Ok(inner)); unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) } } Err(error) => { creation_context.inner = Some(Err(error)); LRESULT(0) } }; } let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak; if ptr.is_null() { return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }; } let inner = unsafe { &*ptr }; let result = if let Some(inner) = inner.upgrade() { if cfg!(debug_assertions) { let inner = std::panic::AssertUnwindSafe(inner); match std::panic::catch_unwind(|| { inner }.handle_msg(hwnd, msg, wparam, lparam)) { Ok(result) => result, Err(_) => std::process::abort(), } } else { inner.handle_msg(hwnd, msg, wparam, lparam) } } else { unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) } }; if msg == WM_NCDESTROY { unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) }; unsafe { drop(Box::from_raw(ptr)) }; } result } /// Copies the username and secret out of a credential returned by `CredReadW`. /// /// Both `UserName` and `CredentialBlob` are optional in Credential Manager and /// come back as null pointers when absent, so they are treated as empty here. /// /// # Safety /// /// A non-null `UserName` must point to a NUL-terminated wide string and a /// non-null `CredentialBlob` must be readable for `CredentialBlobSize` bytes, /// as is the case for credentials returned by `CredReadW`. unsafe fn username_and_password(credential: &CREDENTIALW) -> Result<(String, Vec)> { let username = if credential.UserName.is_null() { String::new() } else { // SAFETY: guaranteed by the caller. unsafe { credential.UserName.to_string()? } }; let password = if credential.CredentialBlob.is_null() { Vec::new() } else { // SAFETY: guaranteed by the caller. unsafe { std::slice::from_raw_parts( credential.CredentialBlob, credential.CredentialBlobSize as usize, ) } .to_vec() }; Ok((username, password)) } #[cfg(test)] mod tests { use std::ffi::{OsStr, OsString}; use crate::{read_from_clipboard, write_to_clipboard}; use gpui::ClipboardItem; use windows::Win32::Security::Credentials::{ CRED_PERSIST_SESSION, CRED_TYPE_GENERIC, CREDENTIALW, CredDeleteW, CredFree, CredReadW, CredWriteW, }; use windows::core::{PCWSTR, PWSTR}; use super::{encode_restart_arguments, username_and_password}; #[test] fn test_read_credential_with_username() { assert_eq!( round_trip_credential(Some("alice"), b"secret"), ("alice".to_string(), b"secret".to_vec()) ); } #[test] fn test_read_credential_without_username() { assert_eq!( round_trip_credential(None, b"secret"), (String::new(), b"secret".to_vec()) ); } fn round_trip_credential(username: Option<&str>, secret: &[u8]) -> (String, Vec) { let mut target_name: Vec = format!( "zed-test-{}-{}", std::process::id(), username.unwrap_or_default() ) .encode_utf16() .chain(Some(0)) .collect(); let mut username: Vec = username .map(|username| username.encode_utf16().chain(Some(0)).collect()) .unwrap_or_default(); let mut secret = secret.to_vec(); let credential = CREDENTIALW { Type: CRED_TYPE_GENERIC, TargetName: PWSTR::from_raw(target_name.as_mut_ptr()), CredentialBlobSize: secret.len() as u32, CredentialBlob: secret.as_mut_ptr(), Persist: CRED_PERSIST_SESSION, UserName: if username.is_empty() { PWSTR::null() } else { PWSTR::from_raw(username.as_mut_ptr()) }, ..CREDENTIALW::default() }; let target_name = PCWSTR::from_raw(target_name.as_ptr()); unsafe { CredWriteW(&credential, 0) }.unwrap(); let mut credentials: *mut CREDENTIALW = std::ptr::null_mut(); unsafe { CredReadW(target_name, CRED_TYPE_GENERIC, None, &mut credentials) }.unwrap(); let result = unsafe { username_and_password(&*credentials) }; unsafe { CredFree(credentials as *const _ as _) }; unsafe { CredDeleteW(target_name, CRED_TYPE_GENERIC, None) }.unwrap(); result.unwrap() } #[test] fn test_encode_restart_arguments() { assert_eq!(encode_restart_arguments(&[]), OsStr::new("")); assert_eq!( encode_restart_arguments(&[ OsString::from("--user-data-dir"), OsString::from(r"C:\Zed Data"), ]), OsStr::new(r#""--user-data-dir" "C:\Zed Data""#) ); assert_eq!( encode_restart_arguments(&[OsString::from(r"C:\")]), OsStr::new(r#""C:\\""#) ); } #[test] fn test_clipboard() { let item = ClipboardItem::new_string("你好,我是张小白".to_string()); write_to_clipboard(item.clone()); assert_eq!(read_from_clipboard(), Some(item)); let item = ClipboardItem::new_string("12345".to_string()); write_to_clipboard(item.clone()); assert_eq!(read_from_clipboard(), Some(item)); let item = ClipboardItem::new_string_with_json_metadata("abcdef".to_string(), vec![3, 4]); write_to_clipboard(item.clone()); assert_eq!(read_from_clipboard(), Some(item)); let item = ClipboardItem::new_string_with_json_metadata("before\0after".to_string(), vec![12]); write_to_clipboard(item); assert_eq!( read_from_clipboard(), Some(ClipboardItem::new_string_with_json_metadata( "before after".to_string(), vec![12], )), ); } }