1use std::{
2 cell::{Cell, RefCell},
3 ffi::OsStr,
4 path::{Path, PathBuf},
5 rc::{Rc, Weak},
6 sync::{
7 Arc,
8 atomic::{AtomicBool, Ordering},
9 },
10};
11
12use ::util::{ResultExt, paths::SanitizedPath};
13use anyhow::{Context as _, Result, anyhow};
14use futures::channel::oneshot::{self, Receiver};
15use itertools::Itertools;
16use parking_lot::RwLock;
17use smallvec::SmallVec;
18use windows::{
19 UI::ViewManagement::UISettings,
20 Win32::{
21 Foundation::*,
22 Graphics::{Direct3D11::ID3D11Device, Gdi::*},
23 Security::Credentials::*,
24 System::{Com::*, LibraryLoader::*, Ole::*, SystemInformation::*},
25 UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
26 },
27 core::*,
28};
29
30use crate::*;
31
32pub(crate) struct WindowsPlatform {
33 inner: Rc<WindowsPlatformInner>,
34 raw_window_handles: Arc<RwLock<SmallVec<[SafeHwnd; 4]>>>,
35 // The below members will never change throughout the entire lifecycle of the app.
36 headless: bool,
37 icon: HICON,
38 background_executor: BackgroundExecutor,
39 foreground_executor: ForegroundExecutor,
40 text_system: Arc<dyn PlatformTextSystem>,
41 direct_write_text_system: Option<Arc<DirectWriteTextSystem>>,
42 windows_version: WindowsVersion,
43 drop_target_helper: Option<IDropTargetHelper>,
44 /// Flag to instruct the `VSyncProvider` thread to invalidate the directx devices
45 /// as resizing them has failed, causing us to have lost at least the render target.
46 invalidate_devices: Arc<AtomicBool>,
47 handle: HWND,
48 disable_direct_composition: bool,
49}
50
51struct WindowsPlatformInner {
52 state: WindowsPlatformState,
53 raw_window_handles: std::sync::Weak<RwLock<SmallVec<[SafeHwnd; 4]>>>,
54 // The below members will never change throughout the entire lifecycle of the app.
55 validation_number: usize,
56 main_receiver: PriorityQueueReceiver<RunnableVariant>,
57 dispatcher: Arc<WindowsDispatcher>,
58}
59
60pub(crate) struct WindowsPlatformState {
61 callbacks: PlatformCallbacks,
62 menus: RefCell<Vec<OwnedMenu>>,
63 jump_list: RefCell<JumpList>,
64 // NOTE: standard cursor handles don't need to close.
65 pub(crate) current_cursor: Cell<Option<HCURSOR>>,
66 directx_devices: RefCell<Option<DirectXDevices>>,
67}
68
69#[derive(Default)]
70struct PlatformCallbacks {
71 open_urls: Cell<Option<Box<dyn FnMut(Vec<String>)>>>,
72 quit: Cell<Option<Box<dyn FnMut()>>>,
73 reopen: Cell<Option<Box<dyn FnMut()>>>,
74 app_menu_action: Cell<Option<Box<dyn FnMut(&dyn Action)>>>,
75 will_open_app_menu: Cell<Option<Box<dyn FnMut()>>>,
76 validate_app_menu_command: Cell<Option<Box<dyn FnMut(&dyn Action) -> bool>>>,
77 keyboard_layout_change: Cell<Option<Box<dyn FnMut()>>>,
78}
79
80impl WindowsPlatformState {
81 fn new(directx_devices: Option<DirectXDevices>) -> Self {
82 let callbacks = PlatformCallbacks::default();
83 let jump_list = JumpList::new();
84 let current_cursor = load_cursor(CursorStyle::Arrow);
85
86 Self {
87 callbacks,
88 jump_list: RefCell::new(jump_list),
89 current_cursor: Cell::new(current_cursor),
90 directx_devices: RefCell::new(directx_devices),
91 menus: RefCell::new(Vec::new()),
92 }
93 }
94}
95
96impl WindowsPlatform {
97 pub(crate) fn new(headless: bool) -> Result<Self> {
98 unsafe {
99 OleInitialize(None).context("unable to initialize Windows OLE")?;
100 }
101 let (directx_devices, text_system, direct_write_text_system) = if !headless {
102 let devices = DirectXDevices::new().context("Creating DirectX devices")?;
103 let dw_text_system = Arc::new(
104 DirectWriteTextSystem::new(&devices)
105 .context("Error creating DirectWriteTextSystem")?,
106 );
107 (
108 Some(devices),
109 dw_text_system.clone() as Arc<dyn PlatformTextSystem>,
110 Some(dw_text_system),
111 )
112 } else {
113 (
114 None,
115 Arc::new(crate::NoopTextSystem::new()) as Arc<dyn PlatformTextSystem>,
116 None,
117 )
118 };
119
120 let (main_sender, main_receiver) = PriorityQueueReceiver::new();
121 let validation_number = if usize::BITS == 64 {
122 rand::random::<u64>() as usize
123 } else {
124 rand::random::<u32>() as usize
125 };
126 let raw_window_handles = Arc::new(RwLock::new(SmallVec::new()));
127
128 register_platform_window_class();
129 let mut context = PlatformWindowCreateContext {
130 inner: None,
131 raw_window_handles: Arc::downgrade(&raw_window_handles),
132 validation_number,
133 main_sender: Some(main_sender),
134 main_receiver: Some(main_receiver),
135 directx_devices,
136 dispatcher: None,
137 };
138 let result = unsafe {
139 CreateWindowExW(
140 WINDOW_EX_STYLE(0),
141 PLATFORM_WINDOW_CLASS_NAME,
142 None,
143 WINDOW_STYLE(0),
144 0,
145 0,
146 0,
147 0,
148 Some(HWND_MESSAGE),
149 None,
150 None,
151 Some(&raw const context as *const _),
152 )
153 };
154 let inner = context
155 .inner
156 .take()
157 .context("CreateWindowExW did not run correctly")??;
158 let dispatcher = context
159 .dispatcher
160 .take()
161 .context("CreateWindowExW did not run correctly")?;
162 let handle = result?;
163
164 let disable_direct_composition = std::env::var(DISABLE_DIRECT_COMPOSITION)
165 .is_ok_and(|value| value == "true" || value == "1");
166 let background_executor = BackgroundExecutor::new(dispatcher.clone());
167 let foreground_executor = ForegroundExecutor::new(dispatcher);
168
169 let drop_target_helper: Option<IDropTargetHelper> = if !headless {
170 Some(unsafe {
171 CoCreateInstance(&CLSID_DragDropHelper, None, CLSCTX_INPROC_SERVER)
172 .context("Error creating drop target helper.")?
173 })
174 } else {
175 None
176 };
177 let icon = if !headless {
178 load_icon().unwrap_or_default()
179 } else {
180 HICON::default()
181 };
182 let windows_version = WindowsVersion::new().context("Error retrieve windows version")?;
183
184 Ok(Self {
185 inner,
186 handle,
187 raw_window_handles,
188 headless,
189 icon,
190 background_executor,
191 foreground_executor,
192 text_system,
193 direct_write_text_system,
194 disable_direct_composition,
195 windows_version,
196 drop_target_helper,
197 invalidate_devices: Arc::new(AtomicBool::new(false)),
198 })
199 }
200
201 pub fn window_from_hwnd(&self, hwnd: HWND) -> Option<Rc<WindowsWindowInner>> {
202 self.raw_window_handles
203 .read()
204 .iter()
205 .find(|entry| entry.as_raw() == hwnd)
206 .and_then(|hwnd| window_from_hwnd(hwnd.as_raw()))
207 }
208
209 #[inline]
210 fn post_message(&self, message: u32, wparam: WPARAM, lparam: LPARAM) {
211 self.raw_window_handles
212 .read()
213 .iter()
214 .for_each(|handle| unsafe {
215 PostMessageW(Some(handle.as_raw()), message, wparam, lparam).log_err();
216 });
217 }
218
219 fn generate_creation_info(&self) -> WindowCreationInfo {
220 WindowCreationInfo {
221 icon: self.icon,
222 executor: self.foreground_executor.clone(),
223 current_cursor: self.inner.state.current_cursor.get(),
224 windows_version: self.windows_version,
225 drop_target_helper: self.drop_target_helper.clone().unwrap(),
226 validation_number: self.inner.validation_number,
227 main_receiver: self.inner.main_receiver.clone(),
228 platform_window_handle: self.handle,
229 disable_direct_composition: self.disable_direct_composition,
230 directx_devices: self.inner.state.directx_devices.borrow().clone().unwrap(),
231 invalidate_devices: self.invalidate_devices.clone(),
232 }
233 }
234
235 fn set_dock_menus(&self, menus: Vec<MenuItem>) {
236 let mut actions = Vec::new();
237 menus.into_iter().for_each(|menu| {
238 if let Some(dock_menu) = DockMenuItem::new(menu).log_err() {
239 actions.push(dock_menu);
240 }
241 });
242 self.inner.state.jump_list.borrow_mut().dock_menus = actions;
243 let borrow = self.inner.state.jump_list.borrow();
244 let dock_menus = borrow
245 .dock_menus
246 .iter()
247 .map(|menu| (menu.name.clone(), menu.description.clone()))
248 .collect::<Vec<_>>();
249 let recent_workspaces = borrow.recent_workspaces.clone();
250 self.background_executor
251 .spawn(async move {
252 update_jump_list(&recent_workspaces, &dock_menus).log_err();
253 })
254 .detach();
255 }
256
257 fn update_jump_list(
258 &self,
259 menus: Vec<MenuItem>,
260 entries: Vec<SmallVec<[PathBuf; 2]>>,
261 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
262 let mut actions = Vec::new();
263 menus.into_iter().for_each(|menu| {
264 if let Some(dock_menu) = DockMenuItem::new(menu).log_err() {
265 actions.push(dock_menu);
266 }
267 });
268 let mut jump_list = self.inner.state.jump_list.borrow_mut();
269 jump_list.dock_menus = actions;
270 jump_list.recent_workspaces = entries.into();
271 let dock_menus = jump_list
272 .dock_menus
273 .iter()
274 .map(|menu| (menu.name.clone(), menu.description.clone()))
275 .collect::<Vec<_>>();
276 let recent_workspaces = jump_list.recent_workspaces.clone();
277 self.background_executor.spawn(async move {
278 update_jump_list(&recent_workspaces, &dock_menus)
279 .log_err()
280 .unwrap_or_default()
281 })
282 }
283
284 fn find_current_active_window(&self) -> Option<HWND> {
285 let active_window_hwnd = unsafe { GetActiveWindow() };
286 if active_window_hwnd.is_invalid() {
287 return None;
288 }
289 self.raw_window_handles
290 .read()
291 .iter()
292 .find(|hwnd| hwnd.as_raw() == active_window_hwnd)
293 .map(|hwnd| hwnd.as_raw())
294 }
295
296 fn begin_vsync_thread(&self) {
297 let Some(directx_devices) = self.inner.state.directx_devices.borrow().clone() else {
298 return;
299 };
300 let Some(direct_write_text_system) = &self.direct_write_text_system else {
301 return;
302 };
303 let mut directx_device = directx_devices;
304 let platform_window: SafeHwnd = self.handle.into();
305 let validation_number = self.inner.validation_number;
306 let all_windows = Arc::downgrade(&self.raw_window_handles);
307 let text_system = Arc::downgrade(direct_write_text_system);
308 let invalidate_devices = self.invalidate_devices.clone();
309
310 std::thread::Builder::new()
311 .name("VSyncProvider".to_owned())
312 .spawn(move || {
313 let vsync_provider = VSyncProvider::new();
314 loop {
315 vsync_provider.wait_for_vsync();
316 if check_device_lost(&directx_device.device)
317 || invalidate_devices.fetch_and(false, Ordering::Acquire)
318 {
319 if let Err(err) = handle_gpu_device_lost(
320 &mut directx_device,
321 platform_window.as_raw(),
322 validation_number,
323 &all_windows,
324 &text_system,
325 ) {
326 panic!("Device lost: {err}");
327 }
328 }
329 let Some(all_windows) = all_windows.upgrade() else {
330 break;
331 };
332 for hwnd in all_windows.read().iter() {
333 unsafe {
334 let _ = RedrawWindow(Some(hwnd.as_raw()), None, None, RDW_INVALIDATE);
335 }
336 }
337 }
338 })
339 .unwrap();
340 }
341}
342
343fn translate_accelerator(msg: &MSG) -> Option<()> {
344 if msg.message != WM_KEYDOWN && msg.message != WM_SYSKEYDOWN {
345 return None;
346 }
347
348 let result = unsafe {
349 SendMessageW(
350 msg.hwnd,
351 WM_GPUI_KEYDOWN,
352 Some(msg.wParam),
353 Some(msg.lParam),
354 )
355 };
356 (result.0 == 0).then_some(())
357}
358
359impl Platform for WindowsPlatform {
360 fn background_executor(&self) -> BackgroundExecutor {
361 self.background_executor.clone()
362 }
363
364 fn foreground_executor(&self) -> ForegroundExecutor {
365 self.foreground_executor.clone()
366 }
367
368 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
369 self.text_system.clone()
370 }
371
372 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
373 Box::new(
374 WindowsKeyboardLayout::new()
375 .log_err()
376 .unwrap_or(WindowsKeyboardLayout::unknown()),
377 )
378 }
379
380 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
381 Rc::new(WindowsKeyboardMapper::new())
382 }
383
384 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
385 self.inner
386 .state
387 .callbacks
388 .keyboard_layout_change
389 .set(Some(callback));
390 }
391
392 fn on_thermal_state_change(&self, _callback: Box<dyn FnMut()>) {}
393
394 fn thermal_state(&self) -> ThermalState {
395 ThermalState::Nominal
396 }
397
398 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
399 on_finish_launching();
400 if !self.headless {
401 self.begin_vsync_thread();
402 }
403
404 let mut msg = MSG::default();
405 unsafe {
406 while GetMessageW(&mut msg, None, 0, 0).as_bool() {
407 if translate_accelerator(&msg).is_none() {
408 _ = TranslateMessage(&msg);
409 DispatchMessageW(&msg);
410 }
411 }
412 }
413
414 self.inner
415 .with_callback(|callbacks| &callbacks.quit, |callback| callback());
416 }
417
418 fn quit(&self) {
419 self.foreground_executor()
420 .spawn(async { unsafe { PostQuitMessage(0) } })
421 .detach();
422 }
423
424 fn restart(&self, binary_path: Option<PathBuf>) {
425 let pid = std::process::id();
426 let Some(app_path) = binary_path.or(self.app_path().log_err()) else {
427 return;
428 };
429 let script = format!(
430 r#"
431 $pidToWaitFor = {}
432 $exePath = "{}"
433
434 while ($true) {{
435 $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
436 if (-not $process) {{
437 Start-Process -FilePath $exePath
438 break
439 }}
440 Start-Sleep -Seconds 0.1
441 }}
442 "#,
443 pid,
444 app_path.display(),
445 );
446
447 // Defer spawning to the foreground executor so it runs after the
448 // current `AppCell` borrow is released. On Windows, `Command::spawn()`
449 // can pump the Win32 message loop (via `CreateProcessW`), which
450 // re-enters message handling possibly resulting in another mutable
451 // borrow of the `AppCell` ending up with a double borrow panic
452 self.foreground_executor
453 .spawn(async move {
454 #[allow(
455 clippy::disallowed_methods,
456 reason = "We are restarting ourselves, using std command thus is fine"
457 )]
458 let restart_process =
459 util::command::new_std_command(util::shell::get_windows_system_shell())
460 .arg("-command")
461 .arg(script)
462 .spawn();
463
464 match restart_process {
465 Ok(_) => unsafe { PostQuitMessage(0) },
466 Err(e) => log::error!("failed to spawn restart script: {:?}", e),
467 }
468 })
469 .detach();
470 }
471
472 fn activate(&self, _ignoring_other_apps: bool) {}
473
474 fn hide(&self) {}
475
476 // todo(windows)
477 fn hide_other_apps(&self) {
478 unimplemented!()
479 }
480
481 // todo(windows)
482 fn unhide_other_apps(&self) {
483 unimplemented!()
484 }
485
486 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
487 WindowsDisplay::displays()
488 }
489
490 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
491 WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
492 }
493
494 #[cfg(feature = "screen-capture")]
495 fn is_screen_capture_supported(&self) -> bool {
496 true
497 }
498
499 #[cfg(feature = "screen-capture")]
500 fn screen_capture_sources(
501 &self,
502 ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
503 crate::platform::scap_screen_capture::scap_screen_sources(&self.foreground_executor)
504 }
505
506 fn active_window(&self) -> Option<AnyWindowHandle> {
507 let active_window_hwnd = unsafe { GetActiveWindow() };
508 self.window_from_hwnd(active_window_hwnd)
509 .map(|inner| inner.handle)
510 }
511
512 fn open_window(
513 &self,
514 handle: AnyWindowHandle,
515 options: WindowParams,
516 ) -> Result<Box<dyn PlatformWindow>> {
517 let window = WindowsWindow::new(handle, options, self.generate_creation_info())?;
518 let handle = window.get_raw_handle();
519 self.raw_window_handles.write().push(handle.into());
520
521 Ok(Box::new(window))
522 }
523
524 fn window_appearance(&self) -> WindowAppearance {
525 system_appearance().log_err().unwrap_or_default()
526 }
527
528 fn open_url(&self, url: &str) {
529 if url.is_empty() {
530 return;
531 }
532 let url_string = url.to_string();
533 self.background_executor()
534 .spawn(async move {
535 open_target(&url_string)
536 .with_context(|| format!("Opening url: {}", url_string))
537 .log_err();
538 })
539 .detach();
540 }
541
542 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
543 self.inner.state.callbacks.open_urls.set(Some(callback));
544 }
545
546 fn prompt_for_paths(
547 &self,
548 options: PathPromptOptions,
549 ) -> Receiver<Result<Option<Vec<PathBuf>>>> {
550 let (tx, rx) = oneshot::channel();
551 let window = self.find_current_active_window();
552 self.foreground_executor()
553 .spawn(async move {
554 let _ = tx.send(file_open_dialog(options, window));
555 })
556 .detach();
557
558 rx
559 }
560
561 fn prompt_for_new_path(
562 &self,
563 directory: &Path,
564 suggested_name: Option<&str>,
565 ) -> Receiver<Result<Option<PathBuf>>> {
566 let directory = directory.to_owned();
567 let suggested_name = suggested_name.map(|s| s.to_owned());
568 let (tx, rx) = oneshot::channel();
569 let window = self.find_current_active_window();
570 self.foreground_executor()
571 .spawn(async move {
572 let _ = tx.send(file_save_dialog(directory, suggested_name, window));
573 })
574 .detach();
575
576 rx
577 }
578
579 fn can_select_mixed_files_and_dirs(&self) -> bool {
580 // The FOS_PICKFOLDERS flag toggles between "only files" and "only folders".
581 false
582 }
583
584 fn reveal_path(&self, path: &Path) {
585 if path.as_os_str().is_empty() {
586 return;
587 }
588 let path = path.to_path_buf();
589 self.background_executor()
590 .spawn(async move {
591 open_target_in_explorer(&path)
592 .with_context(|| format!("Revealing path {} in explorer", path.display()))
593 .log_err();
594 })
595 .detach();
596 }
597
598 fn open_with_system(&self, path: &Path) {
599 if path.as_os_str().is_empty() {
600 return;
601 }
602 let path = path.to_path_buf();
603 self.background_executor()
604 .spawn(async move {
605 open_target(&path)
606 .with_context(|| format!("Opening {} with system", path.display()))
607 .log_err();
608 })
609 .detach();
610 }
611
612 fn on_quit(&self, callback: Box<dyn FnMut()>) {
613 self.inner.state.callbacks.quit.set(Some(callback));
614 }
615
616 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
617 self.inner.state.callbacks.reopen.set(Some(callback));
618 }
619
620 fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
621 *self.inner.state.menus.borrow_mut() = menus.into_iter().map(|menu| menu.owned()).collect();
622 }
623
624 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
625 Some(self.inner.state.menus.borrow().clone())
626 }
627
628 fn set_dock_menu(&self, menus: Vec<MenuItem>, _keymap: &Keymap) {
629 self.set_dock_menus(menus);
630 }
631
632 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
633 self.inner
634 .state
635 .callbacks
636 .app_menu_action
637 .set(Some(callback));
638 }
639
640 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
641 self.inner
642 .state
643 .callbacks
644 .will_open_app_menu
645 .set(Some(callback));
646 }
647
648 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
649 self.inner
650 .state
651 .callbacks
652 .validate_app_menu_command
653 .set(Some(callback));
654 }
655
656 fn app_path(&self) -> Result<PathBuf> {
657 Ok(std::env::current_exe()?)
658 }
659
660 // todo(windows)
661 fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
662 anyhow::bail!("not yet implemented");
663 }
664
665 fn set_cursor_style(&self, style: CursorStyle) {
666 let hcursor = load_cursor(style);
667 if self.inner.state.current_cursor.get().map(|c| c.0) != hcursor.map(|c| c.0) {
668 self.post_message(
669 WM_GPUI_CURSOR_STYLE_CHANGED,
670 WPARAM(0),
671 LPARAM(hcursor.map_or(0, |c| c.0 as isize)),
672 );
673 self.inner.state.current_cursor.set(hcursor);
674 }
675 }
676
677 fn should_auto_hide_scrollbars(&self) -> bool {
678 should_auto_hide_scrollbars().log_err().unwrap_or(false)
679 }
680
681 fn write_to_clipboard(&self, item: ClipboardItem) {
682 write_to_clipboard(item);
683 }
684
685 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
686 read_from_clipboard()
687 }
688
689 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
690 let mut password = password.to_vec();
691 let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
692 let mut target_name = windows_credentials_target_name(url)
693 .encode_utf16()
694 .chain(Some(0))
695 .collect_vec();
696 self.foreground_executor().spawn(async move {
697 let credentials = CREDENTIALW {
698 LastWritten: unsafe { GetSystemTimeAsFileTime() },
699 Flags: CRED_FLAGS(0),
700 Type: CRED_TYPE_GENERIC,
701 TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
702 CredentialBlobSize: password.len() as u32,
703 CredentialBlob: password.as_ptr() as *mut _,
704 Persist: CRED_PERSIST_LOCAL_MACHINE,
705 UserName: PWSTR::from_raw(username.as_mut_ptr()),
706 ..CREDENTIALW::default()
707 };
708 unsafe {
709 CredWriteW(&credentials, 0).map_err(|err| {
710 anyhow!(
711 "Failed to write credentials to Windows Credential Manager: {}",
712 err,
713 )
714 })?;
715 }
716 Ok(())
717 })
718 }
719
720 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
721 let mut target_name = windows_credentials_target_name(url)
722 .encode_utf16()
723 .chain(Some(0))
724 .collect_vec();
725 self.foreground_executor().spawn(async move {
726 let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
727 let result = unsafe {
728 CredReadW(
729 PCWSTR::from_raw(target_name.as_ptr()),
730 CRED_TYPE_GENERIC,
731 None,
732 &mut credentials,
733 )
734 };
735
736 if let Err(err) = result {
737 // ERROR_NOT_FOUND means the credential doesn't exist.
738 // Return Ok(None) to match macOS and Linux behavior.
739 if err.code() == ERROR_NOT_FOUND.to_hresult() {
740 return Ok(None);
741 }
742 return Err(err.into());
743 }
744
745 if credentials.is_null() {
746 Ok(None)
747 } else {
748 let username: String = unsafe { (*credentials).UserName.to_string()? };
749 let credential_blob = unsafe {
750 std::slice::from_raw_parts(
751 (*credentials).CredentialBlob,
752 (*credentials).CredentialBlobSize as usize,
753 )
754 };
755 let password = credential_blob.to_vec();
756 unsafe { CredFree(credentials as *const _ as _) };
757 Ok(Some((username, password)))
758 }
759 })
760 }
761
762 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
763 let mut target_name = windows_credentials_target_name(url)
764 .encode_utf16()
765 .chain(Some(0))
766 .collect_vec();
767 self.foreground_executor().spawn(async move {
768 unsafe {
769 CredDeleteW(
770 PCWSTR::from_raw(target_name.as_ptr()),
771 CRED_TYPE_GENERIC,
772 None,
773 )?
774 };
775 Ok(())
776 })
777 }
778
779 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
780 Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
781 }
782
783 fn perform_dock_menu_action(&self, action: usize) {
784 unsafe {
785 PostMessageW(
786 Some(self.handle),
787 WM_GPUI_DOCK_MENU_ACTION,
788 WPARAM(self.inner.validation_number),
789 LPARAM(action as isize),
790 )
791 .log_err();
792 }
793 }
794
795 fn update_jump_list(
796 &self,
797 menus: Vec<MenuItem>,
798 entries: Vec<SmallVec<[PathBuf; 2]>>,
799 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
800 self.update_jump_list(menus, entries)
801 }
802}
803
804impl WindowsPlatformInner {
805 fn new(context: &mut PlatformWindowCreateContext) -> Result<Rc<Self>> {
806 let state = WindowsPlatformState::new(context.directx_devices.take());
807 Ok(Rc::new(Self {
808 state,
809 raw_window_handles: context.raw_window_handles.clone(),
810 dispatcher: context
811 .dispatcher
812 .as_ref()
813 .context("missing dispatcher")?
814 .clone(),
815 validation_number: context.validation_number,
816 main_receiver: context
817 .main_receiver
818 .take()
819 .context("missing main receiver")?,
820 }))
821 }
822
823 /// Calls `project` to project to the corresponding callback field, removes it from callbacks, calls `f` with the callback and then puts the callback back.
824 fn with_callback<T>(
825 &self,
826 project: impl Fn(&PlatformCallbacks) -> &Cell<Option<T>>,
827 f: impl FnOnce(&mut T),
828 ) {
829 let callback = project(&self.state.callbacks).take();
830 if let Some(mut callback) = callback {
831 f(&mut callback);
832 project(&self.state.callbacks).set(Some(callback));
833 }
834 }
835
836 fn handle_msg(
837 self: &Rc<Self>,
838 handle: HWND,
839 msg: u32,
840 wparam: WPARAM,
841 lparam: LPARAM,
842 ) -> LRESULT {
843 let handled = match msg {
844 WM_GPUI_CLOSE_ONE_WINDOW
845 | WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD
846 | WM_GPUI_DOCK_MENU_ACTION
847 | WM_GPUI_KEYBOARD_LAYOUT_CHANGED
848 | WM_GPUI_GPU_DEVICE_LOST => self.handle_gpui_events(msg, wparam, lparam),
849 _ => None,
850 };
851 if let Some(result) = handled {
852 LRESULT(result)
853 } else {
854 unsafe { DefWindowProcW(handle, msg, wparam, lparam) }
855 }
856 }
857
858 fn handle_gpui_events(&self, message: u32, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
859 if wparam.0 != self.validation_number {
860 log::error!("Wrong validation number while processing message: {message}");
861 return None;
862 }
863 match message {
864 WM_GPUI_CLOSE_ONE_WINDOW => {
865 self.close_one_window(HWND(lparam.0 as _));
866 Some(0)
867 }
868 WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD => self.run_foreground_task(),
869 WM_GPUI_DOCK_MENU_ACTION => self.handle_dock_action_event(lparam.0 as _),
870 WM_GPUI_KEYBOARD_LAYOUT_CHANGED => self.handle_keyboard_layout_change(),
871 WM_GPUI_GPU_DEVICE_LOST => self.handle_device_lost(lparam),
872 _ => unreachable!(),
873 }
874 }
875
876 fn close_one_window(&self, target_window: HWND) -> bool {
877 let Some(all_windows) = self.raw_window_handles.upgrade() else {
878 log::error!("Failed to upgrade raw window handles");
879 return false;
880 };
881 let mut lock = all_windows.write();
882 let index = lock
883 .iter()
884 .position(|handle| handle.as_raw() == target_window)
885 .unwrap();
886 lock.remove(index);
887
888 lock.is_empty()
889 }
890
891 #[inline]
892 fn run_foreground_task(&self) -> Option<isize> {
893 const MAIN_TASK_TIMEOUT: u128 = 10;
894
895 let start = std::time::Instant::now();
896 'tasks: loop {
897 'timeout_loop: loop {
898 if start.elapsed().as_millis() >= MAIN_TASK_TIMEOUT {
899 log::debug!("foreground task timeout reached");
900 // we spent our budget on gpui tasks, we likely have a lot of work queued so drain system events first to stay responsive
901 // then quit out of foreground work to allow us to process other gpui events first before returning back to foreground task work
902 // if we don't we might not for example process window quit events
903 let mut msg = MSG::default();
904 let process_message = |msg: &_| {
905 if translate_accelerator(msg).is_none() {
906 _ = unsafe { TranslateMessage(msg) };
907 unsafe { DispatchMessageW(msg) };
908 }
909 };
910 let peek_msg = |msg: &mut _, msg_kind| unsafe {
911 PeekMessageW(msg, None, 0, 0, PM_REMOVE | msg_kind).as_bool()
912 };
913 // We need to process a paint message here as otherwise we will re-enter `run_foreground_task` before painting if we have work remaining.
914 // The reason for this is that windows prefers custom application message processing over system messages.
915 if peek_msg(&mut msg, PM_QS_PAINT) {
916 process_message(&msg);
917 }
918 while peek_msg(&mut msg, PM_QS_INPUT) {
919 process_message(&msg);
920 }
921 // Allow the main loop to process other gpui events before going back into `run_foreground_task`
922 unsafe {
923 if let Err(_) = PostMessageW(
924 Some(self.dispatcher.platform_window_handle.as_raw()),
925 WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD,
926 WPARAM(self.validation_number),
927 LPARAM(0),
928 ) {
929 self.dispatcher.wake_posted.store(false, Ordering::Release);
930 };
931 }
932 break 'tasks;
933 }
934 let mut main_receiver = self.main_receiver.clone();
935 match main_receiver.try_pop() {
936 Ok(Some(runnable)) => WindowsDispatcher::execute_runnable(runnable),
937 _ => break 'timeout_loop,
938 }
939 }
940
941 // Someone could enqueue a Runnable here. The flag is still true, so they will not PostMessage.
942 // We need to check for those Runnables after we clear the flag.
943 self.dispatcher.wake_posted.store(false, Ordering::Release);
944 let mut main_receiver = self.main_receiver.clone();
945 match main_receiver.try_pop() {
946 Ok(Some(runnable)) => {
947 self.dispatcher.wake_posted.store(true, Ordering::Release);
948
949 WindowsDispatcher::execute_runnable(runnable);
950 }
951 _ => break 'tasks,
952 }
953 }
954
955 Some(0)
956 }
957
958 fn handle_dock_action_event(&self, action_idx: usize) -> Option<isize> {
959 let Some(action) = self
960 .state
961 .jump_list
962 .borrow()
963 .dock_menus
964 .get(action_idx)
965 .map(|dock_menu| dock_menu.action.boxed_clone())
966 else {
967 log::error!("Dock menu for index {action_idx} not found");
968 return Some(1);
969 };
970 self.with_callback(
971 |callbacks| &callbacks.app_menu_action,
972 |callback| callback(&*action),
973 );
974 Some(0)
975 }
976
977 fn handle_keyboard_layout_change(&self) -> Option<isize> {
978 self.with_callback(
979 |callbacks| &callbacks.keyboard_layout_change,
980 |callback| callback(),
981 );
982 Some(0)
983 }
984
985 fn handle_device_lost(&self, lparam: LPARAM) -> Option<isize> {
986 let directx_devices = lparam.0 as *const DirectXDevices;
987 let directx_devices = unsafe { &*directx_devices };
988 self.state.directx_devices.borrow_mut().take();
989 *self.state.directx_devices.borrow_mut() = Some(directx_devices.clone());
990
991 Some(0)
992 }
993}
994
995impl Drop for WindowsPlatform {
996 fn drop(&mut self) {
997 unsafe {
998 DestroyWindow(self.handle)
999 .context("Destroying platform window")
1000 .log_err();
1001 OleUninitialize();
1002 }
1003 }
1004}
1005
1006pub(crate) struct WindowCreationInfo {
1007 pub(crate) icon: HICON,
1008 pub(crate) executor: ForegroundExecutor,
1009 pub(crate) current_cursor: Option<HCURSOR>,
1010 pub(crate) windows_version: WindowsVersion,
1011 pub(crate) drop_target_helper: IDropTargetHelper,
1012 pub(crate) validation_number: usize,
1013 pub(crate) main_receiver: PriorityQueueReceiver<RunnableVariant>,
1014 pub(crate) platform_window_handle: HWND,
1015 pub(crate) disable_direct_composition: bool,
1016 pub(crate) directx_devices: DirectXDevices,
1017 /// Flag to instruct the `VSyncProvider` thread to invalidate the directx devices
1018 /// as resizing them has failed, causing us to have lost at least the render target.
1019 pub(crate) invalidate_devices: Arc<AtomicBool>,
1020}
1021
1022struct PlatformWindowCreateContext {
1023 inner: Option<Result<Rc<WindowsPlatformInner>>>,
1024 raw_window_handles: std::sync::Weak<RwLock<SmallVec<[SafeHwnd; 4]>>>,
1025 validation_number: usize,
1026 main_sender: Option<PriorityQueueSender<RunnableVariant>>,
1027 main_receiver: Option<PriorityQueueReceiver<RunnableVariant>>,
1028 directx_devices: Option<DirectXDevices>,
1029 dispatcher: Option<Arc<WindowsDispatcher>>,
1030}
1031
1032fn open_target(target: impl AsRef<OsStr>) -> Result<()> {
1033 let target = target.as_ref();
1034 let ret = unsafe {
1035 ShellExecuteW(
1036 None,
1037 windows::core::w!("open"),
1038 &HSTRING::from(target),
1039 None,
1040 None,
1041 SW_SHOWDEFAULT,
1042 )
1043 };
1044 if ret.0 as isize <= 32 {
1045 Err(anyhow::anyhow!(
1046 "Unable to open target: {}",
1047 std::io::Error::last_os_error()
1048 ))
1049 } else {
1050 Ok(())
1051 }
1052}
1053
1054fn open_target_in_explorer(target: &Path) -> Result<()> {
1055 let dir = target.parent().context("No parent folder found")?;
1056 let desktop = unsafe { SHGetDesktopFolder()? };
1057
1058 let mut dir_item = std::ptr::null_mut();
1059 unsafe {
1060 desktop.ParseDisplayName(
1061 HWND::default(),
1062 None,
1063 &HSTRING::from(dir),
1064 None,
1065 &mut dir_item,
1066 std::ptr::null_mut(),
1067 )?;
1068 }
1069
1070 let mut file_item = std::ptr::null_mut();
1071 unsafe {
1072 desktop.ParseDisplayName(
1073 HWND::default(),
1074 None,
1075 &HSTRING::from(target),
1076 None,
1077 &mut file_item,
1078 std::ptr::null_mut(),
1079 )?;
1080 }
1081
1082 let highlight = [file_item as *const _];
1083 unsafe { SHOpenFolderAndSelectItems(dir_item as _, Some(&highlight), 0) }.or_else(|err| {
1084 if err.code().0 == ERROR_FILE_NOT_FOUND.0 as i32 {
1085 // On some systems, the above call mysteriously fails with "file not
1086 // found" even though the file is there. In these cases, ShellExecute()
1087 // seems to work as a fallback (although it won't select the file).
1088 open_target(dir).context("Opening target parent folder")
1089 } else {
1090 Err(anyhow::anyhow!("Can not open target path: {}", err))
1091 }
1092 })
1093}
1094
1095fn file_open_dialog(
1096 options: PathPromptOptions,
1097 window: Option<HWND>,
1098) -> Result<Option<Vec<PathBuf>>> {
1099 let folder_dialog: IFileOpenDialog =
1100 unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? };
1101
1102 let mut dialog_options = FOS_FILEMUSTEXIST;
1103 if options.multiple {
1104 dialog_options |= FOS_ALLOWMULTISELECT;
1105 }
1106 if options.directories {
1107 dialog_options |= FOS_PICKFOLDERS;
1108 }
1109
1110 unsafe {
1111 folder_dialog.SetOptions(dialog_options)?;
1112
1113 if let Some(prompt) = options.prompt {
1114 let prompt: &str = &prompt;
1115 folder_dialog.SetOkButtonLabel(&HSTRING::from(prompt))?;
1116 }
1117
1118 if folder_dialog.Show(window).is_err() {
1119 // User cancelled
1120 return Ok(None);
1121 }
1122 }
1123
1124 let results = unsafe { folder_dialog.GetResults()? };
1125 let file_count = unsafe { results.GetCount()? };
1126 if file_count == 0 {
1127 return Ok(None);
1128 }
1129
1130 let mut paths = Vec::with_capacity(file_count as usize);
1131 for i in 0..file_count {
1132 let item = unsafe { results.GetItemAt(i)? };
1133 let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };
1134 paths.push(PathBuf::from(path));
1135 }
1136
1137 Ok(Some(paths))
1138}
1139
1140fn file_save_dialog(
1141 directory: PathBuf,
1142 suggested_name: Option<String>,
1143 window: Option<HWND>,
1144) -> Result<Option<PathBuf>> {
1145 let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };
1146 if !directory.to_string_lossy().is_empty()
1147 && let Some(full_path) = directory
1148 .canonicalize()
1149 .context("failed to canonicalize directory")
1150 .log_err()
1151 {
1152 let full_path = SanitizedPath::new(&full_path);
1153 let full_path_string = full_path.to_string();
1154 let path_item: IShellItem =
1155 unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_string), None)? };
1156 unsafe {
1157 dialog
1158 .SetFolder(&path_item)
1159 .context("failed to set dialog folder")
1160 .log_err()
1161 };
1162 }
1163
1164 if let Some(suggested_name) = suggested_name {
1165 unsafe {
1166 dialog
1167 .SetFileName(&HSTRING::from(suggested_name))
1168 .context("failed to set file name")
1169 .log_err()
1170 };
1171 }
1172
1173 unsafe {
1174 dialog.SetFileTypes(&[Common::COMDLG_FILTERSPEC {
1175 pszName: windows::core::w!("All files"),
1176 pszSpec: windows::core::w!("*.*"),
1177 }])?;
1178 if dialog.Show(window).is_err() {
1179 // User cancelled
1180 return Ok(None);
1181 }
1182 }
1183 let shell_item = unsafe { dialog.GetResult()? };
1184 let file_path_string = unsafe {
1185 let pwstr = shell_item.GetDisplayName(SIGDN_FILESYSPATH)?;
1186 let string = pwstr.to_string()?;
1187 CoTaskMemFree(Some(pwstr.0 as _));
1188 string
1189 };
1190 Ok(Some(PathBuf::from(file_path_string)))
1191}
1192
1193fn load_icon() -> Result<HICON> {
1194 let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
1195 let handle = unsafe {
1196 LoadImageW(
1197 Some(module.into()),
1198 windows::core::PCWSTR(1 as _),
1199 IMAGE_ICON,
1200 0,
1201 0,
1202 LR_DEFAULTSIZE | LR_SHARED,
1203 )
1204 .context("unable to load icon file")?
1205 };
1206 Ok(HICON(handle.0))
1207}
1208
1209#[inline]
1210fn should_auto_hide_scrollbars() -> Result<bool> {
1211 let ui_settings = UISettings::new()?;
1212 Ok(ui_settings.AutoHideScrollBars()?)
1213}
1214
1215fn check_device_lost(device: &ID3D11Device) -> bool {
1216 let device_state = unsafe { device.GetDeviceRemovedReason() };
1217 match device_state {
1218 Ok(_) => false,
1219 Err(err) => {
1220 log::error!("DirectX device lost detected: {:?}", err);
1221 true
1222 }
1223 }
1224}
1225
1226fn handle_gpu_device_lost(
1227 directx_devices: &mut DirectXDevices,
1228 platform_window: HWND,
1229 validation_number: usize,
1230 all_windows: &std::sync::Weak<RwLock<SmallVec<[SafeHwnd; 4]>>>,
1231 text_system: &std::sync::Weak<DirectWriteTextSystem>,
1232) -> Result<()> {
1233 // Here we wait a bit to ensure the system has time to recover from the device lost state.
1234 // If we don't wait, the final drawing result will be blank.
1235 std::thread::sleep(std::time::Duration::from_millis(350));
1236
1237 *directx_devices = try_to_recover_from_device_lost(|| {
1238 DirectXDevices::new().context("Failed to recreate new DirectX devices after device lost")
1239 })?;
1240 log::info!("DirectX devices successfully recreated.");
1241
1242 let lparam = LPARAM(directx_devices as *const _ as _);
1243 unsafe {
1244 SendMessageW(
1245 platform_window,
1246 WM_GPUI_GPU_DEVICE_LOST,
1247 Some(WPARAM(validation_number)),
1248 Some(lparam),
1249 );
1250 }
1251
1252 if let Some(text_system) = text_system.upgrade() {
1253 text_system.handle_gpu_lost(&directx_devices)?;
1254 }
1255 if let Some(all_windows) = all_windows.upgrade() {
1256 for window in all_windows.read().iter() {
1257 unsafe {
1258 SendMessageW(
1259 window.as_raw(),
1260 WM_GPUI_GPU_DEVICE_LOST,
1261 Some(WPARAM(validation_number)),
1262 Some(lparam),
1263 );
1264 }
1265 }
1266 std::thread::sleep(std::time::Duration::from_millis(200));
1267 for window in all_windows.read().iter() {
1268 unsafe {
1269 SendMessageW(
1270 window.as_raw(),
1271 WM_GPUI_FORCE_UPDATE_WINDOW,
1272 Some(WPARAM(validation_number)),
1273 None,
1274 );
1275 }
1276 }
1277 }
1278 Ok(())
1279}
1280
1281const PLATFORM_WINDOW_CLASS_NAME: PCWSTR = w!("Zed::PlatformWindow");
1282
1283fn register_platform_window_class() {
1284 let wc = WNDCLASSW {
1285 lpfnWndProc: Some(window_procedure),
1286 lpszClassName: PCWSTR(PLATFORM_WINDOW_CLASS_NAME.as_ptr()),
1287 ..Default::default()
1288 };
1289 unsafe { RegisterClassW(&wc) };
1290}
1291
1292unsafe extern "system" fn window_procedure(
1293 hwnd: HWND,
1294 msg: u32,
1295 wparam: WPARAM,
1296 lparam: LPARAM,
1297) -> LRESULT {
1298 if msg == WM_NCCREATE {
1299 let params = unsafe { &*(lparam.0 as *const CREATESTRUCTW) };
1300 let creation_context = params.lpCreateParams as *mut PlatformWindowCreateContext;
1301 let creation_context = unsafe { &mut *creation_context };
1302
1303 let Some(main_sender) = creation_context.main_sender.take() else {
1304 creation_context.inner = Some(Err(anyhow!("missing main sender")));
1305 return LRESULT(0);
1306 };
1307 creation_context.dispatcher = Some(Arc::new(WindowsDispatcher::new(
1308 main_sender,
1309 hwnd,
1310 creation_context.validation_number,
1311 )));
1312
1313 return match WindowsPlatformInner::new(creation_context) {
1314 Ok(inner) => {
1315 let weak = Box::new(Rc::downgrade(&inner));
1316 unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
1317 creation_context.inner = Some(Ok(inner));
1318 unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1319 }
1320 Err(error) => {
1321 creation_context.inner = Some(Err(error));
1322 LRESULT(0)
1323 }
1324 };
1325 }
1326
1327 let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsPlatformInner>;
1328 if ptr.is_null() {
1329 return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1330 }
1331 let inner = unsafe { &*ptr };
1332 let result = if let Some(inner) = inner.upgrade() {
1333 inner.handle_msg(hwnd, msg, wparam, lparam)
1334 } else {
1335 unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1336 };
1337
1338 if msg == WM_NCDESTROY {
1339 unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
1340 unsafe { drop(Box::from_raw(ptr)) };
1341 }
1342
1343 result
1344}
1345
1346#[cfg(test)]
1347mod tests {
1348 use crate::{ClipboardItem, read_from_clipboard, write_to_clipboard};
1349
1350 #[test]
1351 fn test_clipboard() {
1352 let item = ClipboardItem::new_string("你好,我是张小白".to_string());
1353 write_to_clipboard(item.clone());
1354 assert_eq!(read_from_clipboard(), Some(item));
1355
1356 let item = ClipboardItem::new_string("12345".to_string());
1357 write_to_clipboard(item.clone());
1358 assert_eq!(read_from_clipboard(), Some(item));
1359
1360 let item = ClipboardItem::new_string_with_json_metadata("abcdef".to_string(), vec![3, 4]);
1361 write_to_clipboard(item.clone());
1362 assert_eq!(read_from_clipboard(), Some(item));
1363 }
1364}