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        self.inner
 346            .with_callback(|callbacks| &mut callbacks.quit, |callback| callback());
 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        if self.inner.state.borrow_mut().current_cursor.map(|c| c.0) != hcursor.map(|c| c.0) {
 581            self.post_message(
 582                WM_GPUI_CURSOR_STYLE_CHANGED,
 583                WPARAM(0),
 584                LPARAM(hcursor.map_or(0, |c| c.0 as isize)),
 585            );
 586            self.inner.state.borrow_mut().current_cursor = hcursor;
 587        }
 588    }
 589
 590    fn should_auto_hide_scrollbars(&self) -> bool {
 591        should_auto_hide_scrollbars().log_err().unwrap_or(false)
 592    }
 593
 594    fn write_to_clipboard(&self, item: ClipboardItem) {
 595        write_to_clipboard(item);
 596    }
 597
 598    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 599        read_from_clipboard()
 600    }
 601
 602    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
 603        let mut password = password.to_vec();
 604        let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
 605        let mut target_name = windows_credentials_target_name(url)
 606            .encode_utf16()
 607            .chain(Some(0))
 608            .collect_vec();
 609        self.foreground_executor().spawn(async move {
 610            let credentials = CREDENTIALW {
 611                LastWritten: unsafe { GetSystemTimeAsFileTime() },
 612                Flags: CRED_FLAGS(0),
 613                Type: CRED_TYPE_GENERIC,
 614                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
 615                CredentialBlobSize: password.len() as u32,
 616                CredentialBlob: password.as_ptr() as *mut _,
 617                Persist: CRED_PERSIST_LOCAL_MACHINE,
 618                UserName: PWSTR::from_raw(username.as_mut_ptr()),
 619                ..CREDENTIALW::default()
 620            };
 621            unsafe { CredWriteW(&credentials, 0) }?;
 622            Ok(())
 623        })
 624    }
 625
 626    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
 627        let mut target_name = windows_credentials_target_name(url)
 628            .encode_utf16()
 629            .chain(Some(0))
 630            .collect_vec();
 631        self.foreground_executor().spawn(async move {
 632            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
 633            unsafe {
 634                CredReadW(
 635                    PCWSTR::from_raw(target_name.as_ptr()),
 636                    CRED_TYPE_GENERIC,
 637                    None,
 638                    &mut credentials,
 639                )?
 640            };
 641
 642            if credentials.is_null() {
 643                Ok(None)
 644            } else {
 645                let username: String = unsafe { (*credentials).UserName.to_string()? };
 646                let credential_blob = unsafe {
 647                    std::slice::from_raw_parts(
 648                        (*credentials).CredentialBlob,
 649                        (*credentials).CredentialBlobSize as usize,
 650                    )
 651                };
 652                let password = credential_blob.to_vec();
 653                unsafe { CredFree(credentials as *const _ as _) };
 654                Ok(Some((username, password)))
 655            }
 656        })
 657    }
 658
 659    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
 660        let mut target_name = windows_credentials_target_name(url)
 661            .encode_utf16()
 662            .chain(Some(0))
 663            .collect_vec();
 664        self.foreground_executor().spawn(async move {
 665            unsafe {
 666                CredDeleteW(
 667                    PCWSTR::from_raw(target_name.as_ptr()),
 668                    CRED_TYPE_GENERIC,
 669                    None,
 670                )?
 671            };
 672            Ok(())
 673        })
 674    }
 675
 676    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
 677        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
 678    }
 679
 680    fn perform_dock_menu_action(&self, action: usize) {
 681        unsafe {
 682            PostMessageW(
 683                Some(self.handle),
 684                WM_GPUI_DOCK_MENU_ACTION,
 685                WPARAM(self.inner.validation_number),
 686                LPARAM(action as isize),
 687            )
 688            .log_err();
 689        }
 690    }
 691
 692    fn update_jump_list(
 693        &self,
 694        menus: Vec<MenuItem>,
 695        entries: Vec<SmallVec<[PathBuf; 2]>>,
 696    ) -> Vec<SmallVec<[PathBuf; 2]>> {
 697        self.update_jump_list(menus, entries)
 698    }
 699}
 700
 701impl WindowsPlatformInner {
 702    fn new(context: &mut PlatformWindowCreateContext) -> Result<Rc<Self>> {
 703        let state = RefCell::new(WindowsPlatformState::new(
 704            context
 705                .directx_devices
 706                .take()
 707                .context("missing directx devices")?,
 708        ));
 709        Ok(Rc::new(Self {
 710            state,
 711            raw_window_handles: context.raw_window_handles.clone(),
 712            dispatcher: context
 713                .dispatcher
 714                .as_ref()
 715                .context("missing dispatcher")?
 716                .clone(),
 717            validation_number: context.validation_number,
 718            main_receiver: context
 719                .main_receiver
 720                .take()
 721                .context("missing main receiver")?,
 722        }))
 723    }
 724
 725    /// Calls `project` to project to the corresponding callback field, removes it from callbacks, calls `f` with the callback and then puts the callback back.
 726    fn with_callback<T>(
 727        &self,
 728        project: impl Fn(&mut PlatformCallbacks) -> &mut Option<T>,
 729        f: impl FnOnce(&mut T),
 730    ) {
 731        if let Some(mut callback) = project(&mut self.state.borrow_mut().callbacks).take() {
 732            f(&mut callback);
 733            *project(&mut self.state.borrow_mut().callbacks) = Some(callback)
 734        }
 735    }
 736
 737    fn handle_msg(
 738        self: &Rc<Self>,
 739        handle: HWND,
 740        msg: u32,
 741        wparam: WPARAM,
 742        lparam: LPARAM,
 743    ) -> LRESULT {
 744        let handled = match msg {
 745            WM_GPUI_CLOSE_ONE_WINDOW
 746            | WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD
 747            | WM_GPUI_DOCK_MENU_ACTION
 748            | WM_GPUI_KEYBOARD_LAYOUT_CHANGED
 749            | WM_GPUI_GPU_DEVICE_LOST => self.handle_gpui_events(msg, wparam, lparam),
 750            _ => None,
 751        };
 752        if let Some(result) = handled {
 753            LRESULT(result)
 754        } else {
 755            unsafe { DefWindowProcW(handle, msg, wparam, lparam) }
 756        }
 757    }
 758
 759    fn handle_gpui_events(&self, message: u32, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
 760        if wparam.0 != self.validation_number {
 761            log::error!("Wrong validation number while processing message: {message}");
 762            return None;
 763        }
 764        match message {
 765            WM_GPUI_CLOSE_ONE_WINDOW => {
 766                self.close_one_window(HWND(lparam.0 as _));
 767                Some(0)
 768            }
 769            WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD => self.run_foreground_task(),
 770            WM_GPUI_DOCK_MENU_ACTION => self.handle_dock_action_event(lparam.0 as _),
 771            WM_GPUI_KEYBOARD_LAYOUT_CHANGED => self.handle_keyboard_layout_change(),
 772            WM_GPUI_GPU_DEVICE_LOST => self.handle_device_lost(lparam),
 773            _ => unreachable!(),
 774        }
 775    }
 776
 777    fn close_one_window(&self, target_window: HWND) -> bool {
 778        let Some(all_windows) = self.raw_window_handles.upgrade() else {
 779            log::error!("Failed to upgrade raw window handles");
 780            return false;
 781        };
 782        let mut lock = all_windows.write();
 783        let index = lock
 784            .iter()
 785            .position(|handle| handle.as_raw() == target_window)
 786            .unwrap();
 787        lock.remove(index);
 788
 789        lock.is_empty()
 790    }
 791
 792    #[inline]
 793    fn run_foreground_task(&self) -> Option<isize> {
 794        loop {
 795            for runnable in self.main_receiver.drain() {
 796                runnable.run();
 797            }
 798
 799            // Someone could enqueue a Runnable here. The flag is still true, so they will not PostMessage.
 800            // We need to check for those Runnables after we clear the flag.
 801            let dispatcher = self.dispatcher.clone();
 802
 803            dispatcher.wake_posted.store(false, Ordering::Release);
 804            match self.main_receiver.try_recv() {
 805                Ok(runnable) => {
 806                    let _ = dispatcher.wake_posted.swap(true, Ordering::AcqRel);
 807                    runnable.run();
 808                    continue;
 809                }
 810                _ => {
 811                    break;
 812                }
 813            }
 814        }
 815
 816        Some(0)
 817    }
 818
 819    fn handle_dock_action_event(&self, action_idx: usize) -> Option<isize> {
 820        let Some(action) = self
 821            .state
 822            .borrow_mut()
 823            .jump_list
 824            .dock_menus
 825            .get(action_idx)
 826            .map(|dock_menu| dock_menu.action.boxed_clone())
 827        else {
 828            log::error!("Dock menu for index {action_idx} not found");
 829            return Some(1);
 830        };
 831        self.with_callback(
 832            |callbacks| &mut callbacks.app_menu_action,
 833            |callback| callback(&*action),
 834        );
 835        Some(0)
 836    }
 837
 838    fn handle_keyboard_layout_change(&self) -> Option<isize> {
 839        self.with_callback(
 840            |callbacks| &mut callbacks.keyboard_layout_change,
 841            |callback| callback(),
 842        );
 843        Some(0)
 844    }
 845
 846    fn handle_device_lost(&self, lparam: LPARAM) -> Option<isize> {
 847        let directx_devices = lparam.0 as *const DirectXDevices;
 848        let directx_devices = unsafe { &*directx_devices };
 849        let mut lock = self.state.borrow_mut();
 850        lock.directx_devices.take();
 851        lock.directx_devices = Some(directx_devices.clone());
 852
 853        Some(0)
 854    }
 855}
 856
 857impl Drop for WindowsPlatform {
 858    fn drop(&mut self) {
 859        unsafe {
 860            DestroyWindow(self.handle)
 861                .context("Destroying platform window")
 862                .log_err();
 863            OleUninitialize();
 864        }
 865    }
 866}
 867
 868pub(crate) struct WindowCreationInfo {
 869    pub(crate) icon: HICON,
 870    pub(crate) executor: ForegroundExecutor,
 871    pub(crate) current_cursor: Option<HCURSOR>,
 872    pub(crate) windows_version: WindowsVersion,
 873    pub(crate) drop_target_helper: IDropTargetHelper,
 874    pub(crate) validation_number: usize,
 875    pub(crate) main_receiver: flume::Receiver<Runnable>,
 876    pub(crate) platform_window_handle: HWND,
 877    pub(crate) disable_direct_composition: bool,
 878    pub(crate) directx_devices: DirectXDevices,
 879}
 880
 881struct PlatformWindowCreateContext {
 882    inner: Option<Result<Rc<WindowsPlatformInner>>>,
 883    raw_window_handles: std::sync::Weak<RwLock<SmallVec<[SafeHwnd; 4]>>>,
 884    validation_number: usize,
 885    main_sender: Option<flume::Sender<Runnable>>,
 886    main_receiver: Option<flume::Receiver<Runnable>>,
 887    directx_devices: Option<DirectXDevices>,
 888    dispatcher: Option<Arc<WindowsDispatcher>>,
 889}
 890
 891fn open_target(target: impl AsRef<OsStr>) -> Result<()> {
 892    let target = target.as_ref();
 893    let ret = unsafe {
 894        ShellExecuteW(
 895            None,
 896            windows::core::w!("open"),
 897            &HSTRING::from(target),
 898            None,
 899            None,
 900            SW_SHOWDEFAULT,
 901        )
 902    };
 903    if ret.0 as isize <= 32 {
 904        Err(anyhow::anyhow!(
 905            "Unable to open target: {}",
 906            std::io::Error::last_os_error()
 907        ))
 908    } else {
 909        Ok(())
 910    }
 911}
 912
 913fn open_target_in_explorer(target: &Path) -> Result<()> {
 914    let dir = target.parent().context("No parent folder found")?;
 915    let desktop = unsafe { SHGetDesktopFolder()? };
 916
 917    let mut dir_item = std::ptr::null_mut();
 918    unsafe {
 919        desktop.ParseDisplayName(
 920            HWND::default(),
 921            None,
 922            &HSTRING::from(dir),
 923            None,
 924            &mut dir_item,
 925            std::ptr::null_mut(),
 926        )?;
 927    }
 928
 929    let mut file_item = std::ptr::null_mut();
 930    unsafe {
 931        desktop.ParseDisplayName(
 932            HWND::default(),
 933            None,
 934            &HSTRING::from(target),
 935            None,
 936            &mut file_item,
 937            std::ptr::null_mut(),
 938        )?;
 939    }
 940
 941    let highlight = [file_item as *const _];
 942    unsafe { SHOpenFolderAndSelectItems(dir_item as _, Some(&highlight), 0) }.or_else(|err| {
 943        if err.code().0 == ERROR_FILE_NOT_FOUND.0 as i32 {
 944            // On some systems, the above call mysteriously fails with "file not
 945            // found" even though the file is there.  In these cases, ShellExecute()
 946            // seems to work as a fallback (although it won't select the file).
 947            open_target(dir).context("Opening target parent folder")
 948        } else {
 949            Err(anyhow::anyhow!("Can not open target path: {}", err))
 950        }
 951    })
 952}
 953
 954fn file_open_dialog(
 955    options: PathPromptOptions,
 956    window: Option<HWND>,
 957) -> Result<Option<Vec<PathBuf>>> {
 958    let folder_dialog: IFileOpenDialog =
 959        unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? };
 960
 961    let mut dialog_options = FOS_FILEMUSTEXIST;
 962    if options.multiple {
 963        dialog_options |= FOS_ALLOWMULTISELECT;
 964    }
 965    if options.directories {
 966        dialog_options |= FOS_PICKFOLDERS;
 967    }
 968
 969    unsafe {
 970        folder_dialog.SetOptions(dialog_options)?;
 971
 972        if let Some(prompt) = options.prompt {
 973            let prompt: &str = &prompt;
 974            folder_dialog.SetOkButtonLabel(&HSTRING::from(prompt))?;
 975        }
 976
 977        if folder_dialog.Show(window).is_err() {
 978            // User cancelled
 979            return Ok(None);
 980        }
 981    }
 982
 983    let results = unsafe { folder_dialog.GetResults()? };
 984    let file_count = unsafe { results.GetCount()? };
 985    if file_count == 0 {
 986        return Ok(None);
 987    }
 988
 989    let mut paths = Vec::with_capacity(file_count as usize);
 990    for i in 0..file_count {
 991        let item = unsafe { results.GetItemAt(i)? };
 992        let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };
 993        paths.push(PathBuf::from(path));
 994    }
 995
 996    Ok(Some(paths))
 997}
 998
 999fn file_save_dialog(
1000    directory: PathBuf,
1001    suggested_name: Option<String>,
1002    window: Option<HWND>,
1003) -> Result<Option<PathBuf>> {
1004    let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };
1005    if !directory.to_string_lossy().is_empty()
1006        && let Some(full_path) = directory
1007            .canonicalize()
1008            .context("failed to canonicalize directory")
1009            .log_err()
1010    {
1011        let full_path = SanitizedPath::new(&full_path);
1012        let full_path_string = full_path.to_string();
1013        let path_item: IShellItem =
1014            unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_string), None)? };
1015        unsafe {
1016            dialog
1017                .SetFolder(&path_item)
1018                .context("failed to set dialog folder")
1019                .log_err()
1020        };
1021    }
1022
1023    if let Some(suggested_name) = suggested_name {
1024        unsafe {
1025            dialog
1026                .SetFileName(&HSTRING::from(suggested_name))
1027                .context("failed to set file name")
1028                .log_err()
1029        };
1030    }
1031
1032    unsafe {
1033        dialog.SetFileTypes(&[Common::COMDLG_FILTERSPEC {
1034            pszName: windows::core::w!("All files"),
1035            pszSpec: windows::core::w!("*.*"),
1036        }])?;
1037        if dialog.Show(window).is_err() {
1038            // User cancelled
1039            return Ok(None);
1040        }
1041    }
1042    let shell_item = unsafe { dialog.GetResult()? };
1043    let file_path_string = unsafe {
1044        let pwstr = shell_item.GetDisplayName(SIGDN_FILESYSPATH)?;
1045        let string = pwstr.to_string()?;
1046        CoTaskMemFree(Some(pwstr.0 as _));
1047        string
1048    };
1049    Ok(Some(PathBuf::from(file_path_string)))
1050}
1051
1052fn load_icon() -> Result<HICON> {
1053    let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
1054    let handle = unsafe {
1055        LoadImageW(
1056            Some(module.into()),
1057            windows::core::PCWSTR(1 as _),
1058            IMAGE_ICON,
1059            0,
1060            0,
1061            LR_DEFAULTSIZE | LR_SHARED,
1062        )
1063        .context("unable to load icon file")?
1064    };
1065    Ok(HICON(handle.0))
1066}
1067
1068#[inline]
1069fn should_auto_hide_scrollbars() -> Result<bool> {
1070    let ui_settings = UISettings::new()?;
1071    Ok(ui_settings.AutoHideScrollBars()?)
1072}
1073
1074fn check_device_lost(device: &ID3D11Device) -> bool {
1075    let device_state = unsafe { device.GetDeviceRemovedReason() };
1076    match device_state {
1077        Ok(_) => false,
1078        Err(err) => {
1079            log::error!("DirectX device lost detected: {:?}", err);
1080            true
1081        }
1082    }
1083}
1084
1085fn handle_gpu_device_lost(
1086    directx_devices: &mut DirectXDevices,
1087    platform_window: HWND,
1088    validation_number: usize,
1089    all_windows: &std::sync::Weak<RwLock<SmallVec<[SafeHwnd; 4]>>>,
1090    text_system: &std::sync::Weak<DirectWriteTextSystem>,
1091) -> Result<()> {
1092    // Here we wait a bit to ensure the system has time to recover from the device lost state.
1093    // If we don't wait, the final drawing result will be blank.
1094    std::thread::sleep(std::time::Duration::from_millis(350));
1095
1096    *directx_devices = try_to_recover_from_device_lost(|| {
1097        DirectXDevices::new().context("Failed to recreate new DirectX devices after device lost")
1098    })?;
1099    log::info!("DirectX devices successfully recreated.");
1100
1101    let lparam = LPARAM(directx_devices as *const _ as _);
1102    unsafe {
1103        SendMessageW(
1104            platform_window,
1105            WM_GPUI_GPU_DEVICE_LOST,
1106            Some(WPARAM(validation_number)),
1107            Some(lparam),
1108        );
1109    }
1110
1111    if let Some(text_system) = text_system.upgrade() {
1112        text_system.handle_gpu_lost(&directx_devices)?;
1113    }
1114    if let Some(all_windows) = all_windows.upgrade() {
1115        for window in all_windows.read().iter() {
1116            unsafe {
1117                SendMessageW(
1118                    window.as_raw(),
1119                    WM_GPUI_GPU_DEVICE_LOST,
1120                    Some(WPARAM(validation_number)),
1121                    Some(lparam),
1122                );
1123            }
1124        }
1125        std::thread::sleep(std::time::Duration::from_millis(200));
1126        for window in all_windows.read().iter() {
1127            unsafe {
1128                SendMessageW(
1129                    window.as_raw(),
1130                    WM_GPUI_FORCE_UPDATE_WINDOW,
1131                    Some(WPARAM(validation_number)),
1132                    None,
1133                );
1134            }
1135        }
1136    }
1137    Ok(())
1138}
1139
1140const PLATFORM_WINDOW_CLASS_NAME: PCWSTR = w!("Zed::PlatformWindow");
1141
1142fn register_platform_window_class() {
1143    let wc = WNDCLASSW {
1144        lpfnWndProc: Some(window_procedure),
1145        lpszClassName: PCWSTR(PLATFORM_WINDOW_CLASS_NAME.as_ptr()),
1146        ..Default::default()
1147    };
1148    unsafe { RegisterClassW(&wc) };
1149}
1150
1151unsafe extern "system" fn window_procedure(
1152    hwnd: HWND,
1153    msg: u32,
1154    wparam: WPARAM,
1155    lparam: LPARAM,
1156) -> LRESULT {
1157    if msg == WM_NCCREATE {
1158        let params = unsafe { &*(lparam.0 as *const CREATESTRUCTW) };
1159        let creation_context = params.lpCreateParams as *mut PlatformWindowCreateContext;
1160        let creation_context = unsafe { &mut *creation_context };
1161
1162        let Some(main_sender) = creation_context.main_sender.take() else {
1163            creation_context.inner = Some(Err(anyhow!("missing main sender")));
1164            return LRESULT(0);
1165        };
1166        creation_context.dispatcher = Some(Arc::new(WindowsDispatcher::new(
1167            main_sender,
1168            hwnd,
1169            creation_context.validation_number,
1170        )));
1171
1172        return match WindowsPlatformInner::new(creation_context) {
1173            Ok(inner) => {
1174                let weak = Box::new(Rc::downgrade(&inner));
1175                unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
1176                creation_context.inner = Some(Ok(inner));
1177                unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1178            }
1179            Err(error) => {
1180                creation_context.inner = Some(Err(error));
1181                LRESULT(0)
1182            }
1183        };
1184    }
1185
1186    let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsPlatformInner>;
1187    if ptr.is_null() {
1188        return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1189    }
1190    let inner = unsafe { &*ptr };
1191    let result = if let Some(inner) = inner.upgrade() {
1192        inner.handle_msg(hwnd, msg, wparam, lparam)
1193    } else {
1194        unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1195    };
1196
1197    if msg == WM_NCDESTROY {
1198        unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
1199        unsafe { drop(Box::from_raw(ptr)) };
1200    }
1201
1202    result
1203}
1204
1205#[cfg(test)]
1206mod tests {
1207    use crate::{ClipboardItem, read_from_clipboard, write_to_clipboard};
1208
1209    #[test]
1210    fn test_clipboard() {
1211        let item = ClipboardItem::new_string("你好,我是张小白".to_string());
1212        write_to_clipboard(item.clone());
1213        assert_eq!(read_from_clipboard(), Some(item));
1214
1215        let item = ClipboardItem::new_string("12345".to_string());
1216        write_to_clipboard(item.clone());
1217        assert_eq!(read_from_clipboard(), Some(item));
1218
1219        let item = ClipboardItem::new_string_with_json_metadata("abcdef".to_string(), vec![3, 4]);
1220        write_to_clipboard(item.clone());
1221        assert_eq!(read_from_clipboard(), Some(item));
1222    }
1223}