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