platform.rs

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