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