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