platform.rs

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