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