platform.rs

   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        )]
 393        // todo(shell): There might be no powershell on the system
 394        let restart_process =
 395            util::command::new_std_command(util::shell::get_windows_system_shell())
 396                .arg("-command")
 397                .arg(script)
 398                .spawn();
 399
 400        match restart_process {
 401            Ok(_) => self.quit(),
 402            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
 403        }
 404    }
 405
 406    fn activate(&self, _ignoring_other_apps: bool) {}
 407
 408    fn hide(&self) {}
 409
 410    // todo(windows)
 411    fn hide_other_apps(&self) {
 412        unimplemented!()
 413    }
 414
 415    // todo(windows)
 416    fn unhide_other_apps(&self) {
 417        unimplemented!()
 418    }
 419
 420    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 421        WindowsDisplay::displays()
 422    }
 423
 424    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 425        WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
 426    }
 427
 428    #[cfg(feature = "screen-capture")]
 429    fn is_screen_capture_supported(&self) -> bool {
 430        true
 431    }
 432
 433    #[cfg(feature = "screen-capture")]
 434    fn screen_capture_sources(
 435        &self,
 436    ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
 437        crate::platform::scap_screen_capture::scap_screen_sources(&self.foreground_executor)
 438    }
 439
 440    fn active_window(&self) -> Option<AnyWindowHandle> {
 441        let active_window_hwnd = unsafe { GetActiveWindow() };
 442        self.window_from_hwnd(active_window_hwnd)
 443            .map(|inner| inner.handle)
 444    }
 445
 446    fn open_window(
 447        &self,
 448        handle: AnyWindowHandle,
 449        options: WindowParams,
 450    ) -> Result<Box<dyn PlatformWindow>> {
 451        let window = WindowsWindow::new(handle, options, self.generate_creation_info())?;
 452        let handle = window.get_raw_handle();
 453        self.raw_window_handles.write().push(handle.into());
 454
 455        Ok(Box::new(window))
 456    }
 457
 458    fn window_appearance(&self) -> WindowAppearance {
 459        system_appearance().log_err().unwrap_or_default()
 460    }
 461
 462    fn open_url(&self, url: &str) {
 463        if url.is_empty() {
 464            return;
 465        }
 466        let url_string = url.to_string();
 467        self.background_executor()
 468            .spawn(async move {
 469                open_target(&url_string)
 470                    .with_context(|| format!("Opening url: {}", url_string))
 471                    .log_err();
 472            })
 473            .detach();
 474    }
 475
 476    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
 477        self.inner.state.borrow_mut().callbacks.open_urls = Some(callback);
 478    }
 479
 480    fn prompt_for_paths(
 481        &self,
 482        options: PathPromptOptions,
 483    ) -> Receiver<Result<Option<Vec<PathBuf>>>> {
 484        let (tx, rx) = oneshot::channel();
 485        let window = self.find_current_active_window();
 486        self.foreground_executor()
 487            .spawn(async move {
 488                let _ = tx.send(file_open_dialog(options, window));
 489            })
 490            .detach();
 491
 492        rx
 493    }
 494
 495    fn prompt_for_new_path(
 496        &self,
 497        directory: &Path,
 498        suggested_name: Option<&str>,
 499    ) -> Receiver<Result<Option<PathBuf>>> {
 500        let directory = directory.to_owned();
 501        let suggested_name = suggested_name.map(|s| s.to_owned());
 502        let (tx, rx) = oneshot::channel();
 503        let window = self.find_current_active_window();
 504        self.foreground_executor()
 505            .spawn(async move {
 506                let _ = tx.send(file_save_dialog(directory, suggested_name, window));
 507            })
 508            .detach();
 509
 510        rx
 511    }
 512
 513    fn can_select_mixed_files_and_dirs(&self) -> bool {
 514        // The FOS_PICKFOLDERS flag toggles between "only files" and "only folders".
 515        false
 516    }
 517
 518    fn reveal_path(&self, path: &Path) {
 519        if path.as_os_str().is_empty() {
 520            return;
 521        }
 522        let path = path.to_path_buf();
 523        self.background_executor()
 524            .spawn(async move {
 525                open_target_in_explorer(&path)
 526                    .with_context(|| format!("Revealing path {} in explorer", path.display()))
 527                    .log_err();
 528            })
 529            .detach();
 530    }
 531
 532    fn open_with_system(&self, path: &Path) {
 533        if path.as_os_str().is_empty() {
 534            return;
 535        }
 536        let path = path.to_path_buf();
 537        self.background_executor()
 538            .spawn(async move {
 539                open_target(&path)
 540                    .with_context(|| format!("Opening {} with system", path.display()))
 541                    .log_err();
 542            })
 543            .detach();
 544    }
 545
 546    fn on_quit(&self, callback: Box<dyn FnMut()>) {
 547        self.inner.state.borrow_mut().callbacks.quit = Some(callback);
 548    }
 549
 550    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
 551        self.inner.state.borrow_mut().callbacks.reopen = Some(callback);
 552    }
 553
 554    fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
 555        self.inner.state.borrow_mut().menus = menus.into_iter().map(|menu| menu.owned()).collect();
 556    }
 557
 558    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
 559        Some(self.inner.state.borrow().menus.clone())
 560    }
 561
 562    fn set_dock_menu(&self, menus: Vec<MenuItem>, _keymap: &Keymap) {
 563        self.set_dock_menus(menus);
 564    }
 565
 566    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
 567        self.inner.state.borrow_mut().callbacks.app_menu_action = Some(callback);
 568    }
 569
 570    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
 571        self.inner.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
 572    }
 573
 574    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
 575        self.inner
 576            .state
 577            .borrow_mut()
 578            .callbacks
 579            .validate_app_menu_command = Some(callback);
 580    }
 581
 582    fn app_path(&self) -> Result<PathBuf> {
 583        Ok(std::env::current_exe()?)
 584    }
 585
 586    // todo(windows)
 587    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
 588        anyhow::bail!("not yet implemented");
 589    }
 590
 591    fn set_cursor_style(&self, style: CursorStyle) {
 592        let hcursor = load_cursor(style);
 593        if self.inner.state.borrow_mut().current_cursor.map(|c| c.0) != hcursor.map(|c| c.0) {
 594            self.post_message(
 595                WM_GPUI_CURSOR_STYLE_CHANGED,
 596                WPARAM(0),
 597                LPARAM(hcursor.map_or(0, |c| c.0 as isize)),
 598            );
 599            self.inner.state.borrow_mut().current_cursor = hcursor;
 600        }
 601    }
 602
 603    fn should_auto_hide_scrollbars(&self) -> bool {
 604        should_auto_hide_scrollbars().log_err().unwrap_or(false)
 605    }
 606
 607    fn write_to_clipboard(&self, item: ClipboardItem) {
 608        write_to_clipboard(item);
 609    }
 610
 611    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 612        read_from_clipboard()
 613    }
 614
 615    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
 616        let mut password = password.to_vec();
 617        let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
 618        let mut target_name = windows_credentials_target_name(url)
 619            .encode_utf16()
 620            .chain(Some(0))
 621            .collect_vec();
 622        self.foreground_executor().spawn(async move {
 623            let credentials = CREDENTIALW {
 624                LastWritten: unsafe { GetSystemTimeAsFileTime() },
 625                Flags: CRED_FLAGS(0),
 626                Type: CRED_TYPE_GENERIC,
 627                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
 628                CredentialBlobSize: password.len() as u32,
 629                CredentialBlob: password.as_ptr() as *mut _,
 630                Persist: CRED_PERSIST_LOCAL_MACHINE,
 631                UserName: PWSTR::from_raw(username.as_mut_ptr()),
 632                ..CREDENTIALW::default()
 633            };
 634            unsafe { CredWriteW(&credentials, 0) }?;
 635            Ok(())
 636        })
 637    }
 638
 639    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
 640        let mut target_name = windows_credentials_target_name(url)
 641            .encode_utf16()
 642            .chain(Some(0))
 643            .collect_vec();
 644        self.foreground_executor().spawn(async move {
 645            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
 646            unsafe {
 647                CredReadW(
 648                    PCWSTR::from_raw(target_name.as_ptr()),
 649                    CRED_TYPE_GENERIC,
 650                    None,
 651                    &mut credentials,
 652                )?
 653            };
 654
 655            if credentials.is_null() {
 656                Ok(None)
 657            } else {
 658                let username: String = unsafe { (*credentials).UserName.to_string()? };
 659                let credential_blob = unsafe {
 660                    std::slice::from_raw_parts(
 661                        (*credentials).CredentialBlob,
 662                        (*credentials).CredentialBlobSize as usize,
 663                    )
 664                };
 665                let password = credential_blob.to_vec();
 666                unsafe { CredFree(credentials as *const _ as _) };
 667                Ok(Some((username, password)))
 668            }
 669        })
 670    }
 671
 672    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
 673        let mut target_name = windows_credentials_target_name(url)
 674            .encode_utf16()
 675            .chain(Some(0))
 676            .collect_vec();
 677        self.foreground_executor().spawn(async move {
 678            unsafe {
 679                CredDeleteW(
 680                    PCWSTR::from_raw(target_name.as_ptr()),
 681                    CRED_TYPE_GENERIC,
 682                    None,
 683                )?
 684            };
 685            Ok(())
 686        })
 687    }
 688
 689    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
 690        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
 691    }
 692
 693    fn perform_dock_menu_action(&self, action: usize) {
 694        unsafe {
 695            PostMessageW(
 696                Some(self.handle),
 697                WM_GPUI_DOCK_MENU_ACTION,
 698                WPARAM(self.inner.validation_number),
 699                LPARAM(action as isize),
 700            )
 701            .log_err();
 702        }
 703    }
 704
 705    fn update_jump_list(
 706        &self,
 707        menus: Vec<MenuItem>,
 708        entries: Vec<SmallVec<[PathBuf; 2]>>,
 709    ) -> Vec<SmallVec<[PathBuf; 2]>> {
 710        self.update_jump_list(menus, entries)
 711    }
 712}
 713
 714impl WindowsPlatformInner {
 715    fn new(context: &mut PlatformWindowCreateContext) -> Result<Rc<Self>> {
 716        let state = RefCell::new(WindowsPlatformState::new(
 717            context
 718                .directx_devices
 719                .take()
 720                .context("missing directx devices")?,
 721        ));
 722        Ok(Rc::new(Self {
 723            state,
 724            raw_window_handles: context.raw_window_handles.clone(),
 725            dispatcher: context
 726                .dispatcher
 727                .as_ref()
 728                .context("missing dispatcher")?
 729                .clone(),
 730            validation_number: context.validation_number,
 731            main_receiver: context
 732                .main_receiver
 733                .take()
 734                .context("missing main receiver")?,
 735        }))
 736    }
 737
 738    /// Calls `project` to project to the corresponding callback field, removes it from callbacks, calls `f` with the callback and then puts the callback back.
 739    fn with_callback<T>(
 740        &self,
 741        project: impl Fn(&mut PlatformCallbacks) -> &mut Option<T>,
 742        f: impl FnOnce(&mut T),
 743    ) {
 744        let callback = project(&mut self.state.borrow_mut().callbacks).take();
 745        if let Some(mut callback) = callback {
 746            f(&mut callback);
 747            *project(&mut self.state.borrow_mut().callbacks) = Some(callback)
 748        }
 749    }
 750
 751    fn handle_msg(
 752        self: &Rc<Self>,
 753        handle: HWND,
 754        msg: u32,
 755        wparam: WPARAM,
 756        lparam: LPARAM,
 757    ) -> LRESULT {
 758        let handled = match msg {
 759            WM_GPUI_CLOSE_ONE_WINDOW
 760            | WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD
 761            | WM_GPUI_DOCK_MENU_ACTION
 762            | WM_GPUI_KEYBOARD_LAYOUT_CHANGED
 763            | WM_GPUI_GPU_DEVICE_LOST => self.handle_gpui_events(msg, wparam, lparam),
 764            _ => None,
 765        };
 766        if let Some(result) = handled {
 767            LRESULT(result)
 768        } else {
 769            unsafe { DefWindowProcW(handle, msg, wparam, lparam) }
 770        }
 771    }
 772
 773    fn handle_gpui_events(&self, message: u32, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
 774        if wparam.0 != self.validation_number {
 775            log::error!("Wrong validation number while processing message: {message}");
 776            return None;
 777        }
 778        match message {
 779            WM_GPUI_CLOSE_ONE_WINDOW => {
 780                self.close_one_window(HWND(lparam.0 as _));
 781                Some(0)
 782            }
 783            WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD => self.run_foreground_task(),
 784            WM_GPUI_DOCK_MENU_ACTION => self.handle_dock_action_event(lparam.0 as _),
 785            WM_GPUI_KEYBOARD_LAYOUT_CHANGED => self.handle_keyboard_layout_change(),
 786            WM_GPUI_GPU_DEVICE_LOST => self.handle_device_lost(lparam),
 787            _ => unreachable!(),
 788        }
 789    }
 790
 791    fn close_one_window(&self, target_window: HWND) -> bool {
 792        let Some(all_windows) = self.raw_window_handles.upgrade() else {
 793            log::error!("Failed to upgrade raw window handles");
 794            return false;
 795        };
 796        let mut lock = all_windows.write();
 797        let index = lock
 798            .iter()
 799            .position(|handle| handle.as_raw() == target_window)
 800            .unwrap();
 801        lock.remove(index);
 802
 803        lock.is_empty()
 804    }
 805
 806    #[inline]
 807    fn run_foreground_task(&self) -> Option<isize> {
 808        loop {
 809            for runnable in self.main_receiver.drain() {
 810                WindowsDispatcher::execute_runnable(runnable);
 811            }
 812
 813            // Someone could enqueue a Runnable here. The flag is still true, so they will not PostMessage.
 814            // We need to check for those Runnables after we clear the flag.
 815            let dispatcher = self.dispatcher.clone();
 816
 817            dispatcher.wake_posted.store(false, Ordering::Release);
 818            match self.main_receiver.try_recv() {
 819                Ok(runnable) => {
 820                    let _ = dispatcher.wake_posted.swap(true, Ordering::AcqRel);
 821
 822                    WindowsDispatcher::execute_runnable(runnable);
 823                    continue;
 824                }
 825                _ => {
 826                    break;
 827                }
 828            }
 829        }
 830
 831        Some(0)
 832    }
 833
 834    fn handle_dock_action_event(&self, action_idx: usize) -> Option<isize> {
 835        let Some(action) = self
 836            .state
 837            .borrow_mut()
 838            .jump_list
 839            .dock_menus
 840            .get(action_idx)
 841            .map(|dock_menu| dock_menu.action.boxed_clone())
 842        else {
 843            log::error!("Dock menu for index {action_idx} not found");
 844            return Some(1);
 845        };
 846        self.with_callback(
 847            |callbacks| &mut callbacks.app_menu_action,
 848            |callback| callback(&*action),
 849        );
 850        Some(0)
 851    }
 852
 853    fn handle_keyboard_layout_change(&self) -> Option<isize> {
 854        self.with_callback(
 855            |callbacks| &mut callbacks.keyboard_layout_change,
 856            |callback| callback(),
 857        );
 858        Some(0)
 859    }
 860
 861    fn handle_device_lost(&self, lparam: LPARAM) -> Option<isize> {
 862        let directx_devices = lparam.0 as *const DirectXDevices;
 863        let directx_devices = unsafe { &*directx_devices };
 864        let mut lock = self.state.borrow_mut();
 865        lock.directx_devices.take();
 866        lock.directx_devices = Some(directx_devices.clone());
 867
 868        Some(0)
 869    }
 870}
 871
 872impl Drop for WindowsPlatform {
 873    fn drop(&mut self) {
 874        unsafe {
 875            DestroyWindow(self.handle)
 876                .context("Destroying platform window")
 877                .log_err();
 878            OleUninitialize();
 879        }
 880    }
 881}
 882
 883pub(crate) struct WindowCreationInfo {
 884    pub(crate) icon: HICON,
 885    pub(crate) executor: ForegroundExecutor,
 886    pub(crate) current_cursor: Option<HCURSOR>,
 887    pub(crate) windows_version: WindowsVersion,
 888    pub(crate) drop_target_helper: IDropTargetHelper,
 889    pub(crate) validation_number: usize,
 890    pub(crate) main_receiver: flume::Receiver<RunnableVariant>,
 891    pub(crate) platform_window_handle: HWND,
 892    pub(crate) disable_direct_composition: bool,
 893    pub(crate) directx_devices: DirectXDevices,
 894    /// Flag to instruct the `VSyncProvider` thread to invalidate the directx devices
 895    /// as resizing them has failed, causing us to have lost at least the render target.
 896    pub(crate) invalidate_devices: Arc<AtomicBool>,
 897}
 898
 899struct PlatformWindowCreateContext {
 900    inner: Option<Result<Rc<WindowsPlatformInner>>>,
 901    raw_window_handles: std::sync::Weak<RwLock<SmallVec<[SafeHwnd; 4]>>>,
 902    validation_number: usize,
 903    main_sender: Option<flume::Sender<RunnableVariant>>,
 904    main_receiver: Option<flume::Receiver<RunnableVariant>>,
 905    directx_devices: Option<DirectXDevices>,
 906    dispatcher: Option<Arc<WindowsDispatcher>>,
 907}
 908
 909fn open_target(target: impl AsRef<OsStr>) -> Result<()> {
 910    let target = target.as_ref();
 911    let ret = unsafe {
 912        ShellExecuteW(
 913            None,
 914            windows::core::w!("open"),
 915            &HSTRING::from(target),
 916            None,
 917            None,
 918            SW_SHOWDEFAULT,
 919        )
 920    };
 921    if ret.0 as isize <= 32 {
 922        Err(anyhow::anyhow!(
 923            "Unable to open target: {}",
 924            std::io::Error::last_os_error()
 925        ))
 926    } else {
 927        Ok(())
 928    }
 929}
 930
 931fn open_target_in_explorer(target: &Path) -> Result<()> {
 932    let dir = target.parent().context("No parent folder found")?;
 933    let desktop = unsafe { SHGetDesktopFolder()? };
 934
 935    let mut dir_item = std::ptr::null_mut();
 936    unsafe {
 937        desktop.ParseDisplayName(
 938            HWND::default(),
 939            None,
 940            &HSTRING::from(dir),
 941            None,
 942            &mut dir_item,
 943            std::ptr::null_mut(),
 944        )?;
 945    }
 946
 947    let mut file_item = std::ptr::null_mut();
 948    unsafe {
 949        desktop.ParseDisplayName(
 950            HWND::default(),
 951            None,
 952            &HSTRING::from(target),
 953            None,
 954            &mut file_item,
 955            std::ptr::null_mut(),
 956        )?;
 957    }
 958
 959    let highlight = [file_item as *const _];
 960    unsafe { SHOpenFolderAndSelectItems(dir_item as _, Some(&highlight), 0) }.or_else(|err| {
 961        if err.code().0 == ERROR_FILE_NOT_FOUND.0 as i32 {
 962            // On some systems, the above call mysteriously fails with "file not
 963            // found" even though the file is there.  In these cases, ShellExecute()
 964            // seems to work as a fallback (although it won't select the file).
 965            open_target(dir).context("Opening target parent folder")
 966        } else {
 967            Err(anyhow::anyhow!("Can not open target path: {}", err))
 968        }
 969    })
 970}
 971
 972fn file_open_dialog(
 973    options: PathPromptOptions,
 974    window: Option<HWND>,
 975) -> Result<Option<Vec<PathBuf>>> {
 976    let folder_dialog: IFileOpenDialog =
 977        unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? };
 978
 979    let mut dialog_options = FOS_FILEMUSTEXIST;
 980    if options.multiple {
 981        dialog_options |= FOS_ALLOWMULTISELECT;
 982    }
 983    if options.directories {
 984        dialog_options |= FOS_PICKFOLDERS;
 985    }
 986
 987    unsafe {
 988        folder_dialog.SetOptions(dialog_options)?;
 989
 990        if let Some(prompt) = options.prompt {
 991            let prompt: &str = &prompt;
 992            folder_dialog.SetOkButtonLabel(&HSTRING::from(prompt))?;
 993        }
 994
 995        if folder_dialog.Show(window).is_err() {
 996            // User cancelled
 997            return Ok(None);
 998        }
 999    }
1000
1001    let results = unsafe { folder_dialog.GetResults()? };
1002    let file_count = unsafe { results.GetCount()? };
1003    if file_count == 0 {
1004        return Ok(None);
1005    }
1006
1007    let mut paths = Vec::with_capacity(file_count as usize);
1008    for i in 0..file_count {
1009        let item = unsafe { results.GetItemAt(i)? };
1010        let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };
1011        paths.push(PathBuf::from(path));
1012    }
1013
1014    Ok(Some(paths))
1015}
1016
1017fn file_save_dialog(
1018    directory: PathBuf,
1019    suggested_name: Option<String>,
1020    window: Option<HWND>,
1021) -> Result<Option<PathBuf>> {
1022    let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };
1023    if !directory.to_string_lossy().is_empty()
1024        && let Some(full_path) = directory
1025            .canonicalize()
1026            .context("failed to canonicalize directory")
1027            .log_err()
1028    {
1029        let full_path = SanitizedPath::new(&full_path);
1030        let full_path_string = full_path.to_string();
1031        let path_item: IShellItem =
1032            unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_string), None)? };
1033        unsafe {
1034            dialog
1035                .SetFolder(&path_item)
1036                .context("failed to set dialog folder")
1037                .log_err()
1038        };
1039    }
1040
1041    if let Some(suggested_name) = suggested_name {
1042        unsafe {
1043            dialog
1044                .SetFileName(&HSTRING::from(suggested_name))
1045                .context("failed to set file name")
1046                .log_err()
1047        };
1048    }
1049
1050    unsafe {
1051        dialog.SetFileTypes(&[Common::COMDLG_FILTERSPEC {
1052            pszName: windows::core::w!("All files"),
1053            pszSpec: windows::core::w!("*.*"),
1054        }])?;
1055        if dialog.Show(window).is_err() {
1056            // User cancelled
1057            return Ok(None);
1058        }
1059    }
1060    let shell_item = unsafe { dialog.GetResult()? };
1061    let file_path_string = unsafe {
1062        let pwstr = shell_item.GetDisplayName(SIGDN_FILESYSPATH)?;
1063        let string = pwstr.to_string()?;
1064        CoTaskMemFree(Some(pwstr.0 as _));
1065        string
1066    };
1067    Ok(Some(PathBuf::from(file_path_string)))
1068}
1069
1070fn load_icon() -> Result<HICON> {
1071    let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
1072    let handle = unsafe {
1073        LoadImageW(
1074            Some(module.into()),
1075            windows::core::PCWSTR(1 as _),
1076            IMAGE_ICON,
1077            0,
1078            0,
1079            LR_DEFAULTSIZE | LR_SHARED,
1080        )
1081        .context("unable to load icon file")?
1082    };
1083    Ok(HICON(handle.0))
1084}
1085
1086#[inline]
1087fn should_auto_hide_scrollbars() -> Result<bool> {
1088    let ui_settings = UISettings::new()?;
1089    Ok(ui_settings.AutoHideScrollBars()?)
1090}
1091
1092fn check_device_lost(device: &ID3D11Device) -> bool {
1093    let device_state = unsafe { device.GetDeviceRemovedReason() };
1094    match device_state {
1095        Ok(_) => false,
1096        Err(err) => {
1097            log::error!("DirectX device lost detected: {:?}", err);
1098            true
1099        }
1100    }
1101}
1102
1103fn handle_gpu_device_lost(
1104    directx_devices: &mut DirectXDevices,
1105    platform_window: HWND,
1106    validation_number: usize,
1107    all_windows: &std::sync::Weak<RwLock<SmallVec<[SafeHwnd; 4]>>>,
1108    text_system: &std::sync::Weak<DirectWriteTextSystem>,
1109) -> Result<()> {
1110    // Here we wait a bit to ensure the system has time to recover from the device lost state.
1111    // If we don't wait, the final drawing result will be blank.
1112    std::thread::sleep(std::time::Duration::from_millis(350));
1113
1114    *directx_devices = try_to_recover_from_device_lost(|| {
1115        DirectXDevices::new().context("Failed to recreate new DirectX devices after device lost")
1116    })?;
1117    log::info!("DirectX devices successfully recreated.");
1118
1119    let lparam = LPARAM(directx_devices as *const _ as _);
1120    unsafe {
1121        SendMessageW(
1122            platform_window,
1123            WM_GPUI_GPU_DEVICE_LOST,
1124            Some(WPARAM(validation_number)),
1125            Some(lparam),
1126        );
1127    }
1128
1129    if let Some(text_system) = text_system.upgrade() {
1130        text_system.handle_gpu_lost(&directx_devices)?;
1131    }
1132    if let Some(all_windows) = all_windows.upgrade() {
1133        for window in all_windows.read().iter() {
1134            unsafe {
1135                SendMessageW(
1136                    window.as_raw(),
1137                    WM_GPUI_GPU_DEVICE_LOST,
1138                    Some(WPARAM(validation_number)),
1139                    Some(lparam),
1140                );
1141            }
1142        }
1143        std::thread::sleep(std::time::Duration::from_millis(200));
1144        for window in all_windows.read().iter() {
1145            unsafe {
1146                SendMessageW(
1147                    window.as_raw(),
1148                    WM_GPUI_FORCE_UPDATE_WINDOW,
1149                    Some(WPARAM(validation_number)),
1150                    None,
1151                );
1152            }
1153        }
1154    }
1155    Ok(())
1156}
1157
1158const PLATFORM_WINDOW_CLASS_NAME: PCWSTR = w!("Zed::PlatformWindow");
1159
1160fn register_platform_window_class() {
1161    let wc = WNDCLASSW {
1162        lpfnWndProc: Some(window_procedure),
1163        lpszClassName: PCWSTR(PLATFORM_WINDOW_CLASS_NAME.as_ptr()),
1164        ..Default::default()
1165    };
1166    unsafe { RegisterClassW(&wc) };
1167}
1168
1169unsafe extern "system" fn window_procedure(
1170    hwnd: HWND,
1171    msg: u32,
1172    wparam: WPARAM,
1173    lparam: LPARAM,
1174) -> LRESULT {
1175    if msg == WM_NCCREATE {
1176        let params = unsafe { &*(lparam.0 as *const CREATESTRUCTW) };
1177        let creation_context = params.lpCreateParams as *mut PlatformWindowCreateContext;
1178        let creation_context = unsafe { &mut *creation_context };
1179
1180        let Some(main_sender) = creation_context.main_sender.take() else {
1181            creation_context.inner = Some(Err(anyhow!("missing main sender")));
1182            return LRESULT(0);
1183        };
1184        creation_context.dispatcher = Some(Arc::new(WindowsDispatcher::new(
1185            main_sender,
1186            hwnd,
1187            creation_context.validation_number,
1188        )));
1189
1190        return match WindowsPlatformInner::new(creation_context) {
1191            Ok(inner) => {
1192                let weak = Box::new(Rc::downgrade(&inner));
1193                unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
1194                creation_context.inner = Some(Ok(inner));
1195                unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1196            }
1197            Err(error) => {
1198                creation_context.inner = Some(Err(error));
1199                LRESULT(0)
1200            }
1201        };
1202    }
1203
1204    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsPlatformInner>;
1205    if ptr.is_null() {
1206        return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1207    }
1208    let inner = unsafe { &*ptr };
1209    let result = if let Some(inner) = inner.upgrade() {
1210        inner.handle_msg(hwnd, msg, wparam, lparam)
1211    } else {
1212        unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1213    };
1214
1215    if msg == WM_NCDESTROY {
1216        unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
1217        unsafe { drop(Box::from_raw(ptr)) };
1218    }
1219
1220    result
1221}
1222
1223#[cfg(test)]
1224mod tests {
1225    use crate::{ClipboardItem, read_from_clipboard, write_to_clipboard};
1226
1227    #[test]
1228    fn test_clipboard() {
1229        let item = ClipboardItem::new_string("你好,我是张小白".to_string());
1230        write_to_clipboard(item.clone());
1231        assert_eq!(read_from_clipboard(), Some(item));
1232
1233        let item = ClipboardItem::new_string("12345".to_string());
1234        write_to_clipboard(item.clone());
1235        assert_eq!(read_from_clipboard(), Some(item));
1236
1237        let item = ClipboardItem::new_string_with_json_metadata("abcdef".to_string(), vec![3, 4]);
1238        write_to_clipboard(item.clone());
1239        assert_eq!(read_from_clipboard(), Some(item));
1240    }
1241}