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