platform.rs

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