platform.rs

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