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