platform.rs

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