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
 275fn translate_accelerator(msg: &MSG) -> Option<()> {
 276    if msg.message != WM_KEYDOWN && msg.message != WM_SYSKEYDOWN {
 277        return None;
 278    }
 279
 280    let result = unsafe {
 281        SendMessageW(
 282            msg.hwnd,
 283            WM_GPUI_KEYDOWN,
 284            Some(msg.wParam),
 285            Some(msg.lParam),
 286        )
 287    };
 288    (result.0 == 0).then_some(())
 289}
 290
 291impl Platform for WindowsPlatform {
 292    fn background_executor(&self) -> BackgroundExecutor {
 293        self.background_executor.clone()
 294    }
 295
 296    fn foreground_executor(&self) -> ForegroundExecutor {
 297        self.foreground_executor.clone()
 298    }
 299
 300    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
 301        self.text_system.clone()
 302    }
 303
 304    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
 305        Box::new(
 306            WindowsKeyboardLayout::new()
 307                .log_err()
 308                .unwrap_or(WindowsKeyboardLayout::unknown()),
 309        )
 310    }
 311
 312    fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
 313        Rc::new(WindowsKeyboardMapper::new())
 314    }
 315
 316    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
 317        self.inner
 318            .state
 319            .borrow_mut()
 320            .callbacks
 321            .keyboard_layout_change = Some(callback);
 322    }
 323
 324    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
 325        on_finish_launching();
 326        self.begin_vsync_thread();
 327
 328        let mut msg = MSG::default();
 329        unsafe {
 330            while GetMessageW(&mut msg, None, 0, 0).as_bool() {
 331                if translate_accelerator(&msg).is_none() {
 332                    _ = TranslateMessage(&msg);
 333                    DispatchMessageW(&msg);
 334                }
 335            }
 336        }
 337
 338        if let Some(ref mut callback) = self.inner.state.borrow_mut().callbacks.quit {
 339            callback();
 340        }
 341    }
 342
 343    fn quit(&self) {
 344        self.foreground_executor()
 345            .spawn(async { unsafe { PostQuitMessage(0) } })
 346            .detach();
 347    }
 348
 349    fn restart(&self, binary_path: Option<PathBuf>) {
 350        let pid = std::process::id();
 351        let Some(app_path) = binary_path.or(self.app_path().log_err()) else {
 352            return;
 353        };
 354        let script = format!(
 355            r#"
 356            $pidToWaitFor = {}
 357            $exePath = "{}"
 358
 359            while ($true) {{
 360                $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
 361                if (-not $process) {{
 362                    Start-Process -FilePath $exePath
 363                    break
 364                }}
 365                Start-Sleep -Seconds 0.1
 366            }}
 367            "#,
 368            pid,
 369            app_path.display(),
 370        );
 371
 372        #[allow(
 373            clippy::disallowed_methods,
 374            reason = "We are restarting ourselves, using std command thus is fine"
 375        )]
 376        let restart_process = util::command::new_std_command("powershell.exe")
 377            .arg("-command")
 378            .arg(script)
 379            .spawn();
 380
 381        match restart_process {
 382            Ok(_) => self.quit(),
 383            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
 384        }
 385    }
 386
 387    fn activate(&self, _ignoring_other_apps: bool) {}
 388
 389    fn hide(&self) {}
 390
 391    // todo(windows)
 392    fn hide_other_apps(&self) {
 393        unimplemented!()
 394    }
 395
 396    // todo(windows)
 397    fn unhide_other_apps(&self) {
 398        unimplemented!()
 399    }
 400
 401    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 402        WindowsDisplay::displays()
 403    }
 404
 405    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 406        WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
 407    }
 408
 409    #[cfg(feature = "screen-capture")]
 410    fn is_screen_capture_supported(&self) -> bool {
 411        true
 412    }
 413
 414    #[cfg(feature = "screen-capture")]
 415    fn screen_capture_sources(
 416        &self,
 417    ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
 418        crate::platform::scap_screen_capture::scap_screen_sources(&self.foreground_executor)
 419    }
 420
 421    fn active_window(&self) -> Option<AnyWindowHandle> {
 422        let active_window_hwnd = unsafe { GetActiveWindow() };
 423        self.window_from_hwnd(active_window_hwnd)
 424            .map(|inner| inner.handle)
 425    }
 426
 427    fn open_window(
 428        &self,
 429        handle: AnyWindowHandle,
 430        options: WindowParams,
 431    ) -> Result<Box<dyn PlatformWindow>> {
 432        let window = WindowsWindow::new(handle, options, self.generate_creation_info())?;
 433        let handle = window.get_raw_handle();
 434        self.raw_window_handles.write().push(handle.into());
 435
 436        Ok(Box::new(window))
 437    }
 438
 439    fn window_appearance(&self) -> WindowAppearance {
 440        system_appearance().log_err().unwrap_or_default()
 441    }
 442
 443    fn open_url(&self, url: &str) {
 444        if url.is_empty() {
 445            return;
 446        }
 447        let url_string = url.to_string();
 448        self.background_executor()
 449            .spawn(async move {
 450                open_target(&url_string)
 451                    .with_context(|| format!("Opening url: {}", url_string))
 452                    .log_err();
 453            })
 454            .detach();
 455    }
 456
 457    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
 458        self.inner.state.borrow_mut().callbacks.open_urls = Some(callback);
 459    }
 460
 461    fn prompt_for_paths(
 462        &self,
 463        options: PathPromptOptions,
 464    ) -> Receiver<Result<Option<Vec<PathBuf>>>> {
 465        let (tx, rx) = oneshot::channel();
 466        let window = self.find_current_active_window();
 467        self.foreground_executor()
 468            .spawn(async move {
 469                let _ = tx.send(file_open_dialog(options, window));
 470            })
 471            .detach();
 472
 473        rx
 474    }
 475
 476    fn prompt_for_new_path(
 477        &self,
 478        directory: &Path,
 479        suggested_name: Option<&str>,
 480    ) -> Receiver<Result<Option<PathBuf>>> {
 481        let directory = directory.to_owned();
 482        let suggested_name = suggested_name.map(|s| s.to_owned());
 483        let (tx, rx) = oneshot::channel();
 484        let window = self.find_current_active_window();
 485        self.foreground_executor()
 486            .spawn(async move {
 487                let _ = tx.send(file_save_dialog(directory, suggested_name, window));
 488            })
 489            .detach();
 490
 491        rx
 492    }
 493
 494    fn can_select_mixed_files_and_dirs(&self) -> bool {
 495        // The FOS_PICKFOLDERS flag toggles between "only files" and "only folders".
 496        false
 497    }
 498
 499    fn reveal_path(&self, path: &Path) {
 500        if path.as_os_str().is_empty() {
 501            return;
 502        }
 503        let path = path.to_path_buf();
 504        self.background_executor()
 505            .spawn(async move {
 506                open_target_in_explorer(&path)
 507                    .with_context(|| format!("Revealing path {} in explorer", path.display()))
 508                    .log_err();
 509            })
 510            .detach();
 511    }
 512
 513    fn open_with_system(&self, path: &Path) {
 514        if path.as_os_str().is_empty() {
 515            return;
 516        }
 517        let path = path.to_path_buf();
 518        self.background_executor()
 519            .spawn(async move {
 520                open_target(&path)
 521                    .with_context(|| format!("Opening {} with system", path.display()))
 522                    .log_err();
 523            })
 524            .detach();
 525    }
 526
 527    fn on_quit(&self, callback: Box<dyn FnMut()>) {
 528        self.inner.state.borrow_mut().callbacks.quit = Some(callback);
 529    }
 530
 531    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
 532        self.inner.state.borrow_mut().callbacks.reopen = Some(callback);
 533    }
 534
 535    fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
 536        self.inner.state.borrow_mut().menus = menus.into_iter().map(|menu| menu.owned()).collect();
 537    }
 538
 539    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
 540        Some(self.inner.state.borrow().menus.clone())
 541    }
 542
 543    fn set_dock_menu(&self, menus: Vec<MenuItem>, _keymap: &Keymap) {
 544        self.set_dock_menus(menus);
 545    }
 546
 547    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
 548        self.inner.state.borrow_mut().callbacks.app_menu_action = Some(callback);
 549    }
 550
 551    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
 552        self.inner.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
 553    }
 554
 555    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
 556        self.inner
 557            .state
 558            .borrow_mut()
 559            .callbacks
 560            .validate_app_menu_command = Some(callback);
 561    }
 562
 563    fn app_path(&self) -> Result<PathBuf> {
 564        Ok(std::env::current_exe()?)
 565    }
 566
 567    // todo(windows)
 568    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
 569        anyhow::bail!("not yet implemented");
 570    }
 571
 572    fn set_cursor_style(&self, style: CursorStyle) {
 573        let hcursor = load_cursor(style);
 574        let mut lock = self.inner.state.borrow_mut();
 575        if lock.current_cursor.map(|c| c.0) != hcursor.map(|c| c.0) {
 576            self.post_message(
 577                WM_GPUI_CURSOR_STYLE_CHANGED,
 578                WPARAM(0),
 579                LPARAM(hcursor.map_or(0, |c| c.0 as isize)),
 580            );
 581            lock.current_cursor = hcursor;
 582        }
 583    }
 584
 585    fn should_auto_hide_scrollbars(&self) -> bool {
 586        should_auto_hide_scrollbars().log_err().unwrap_or(false)
 587    }
 588
 589    fn write_to_clipboard(&self, item: ClipboardItem) {
 590        write_to_clipboard(item);
 591    }
 592
 593    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 594        read_from_clipboard()
 595    }
 596
 597    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
 598        let mut password = password.to_vec();
 599        let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
 600        let mut target_name = windows_credentials_target_name(url)
 601            .encode_utf16()
 602            .chain(Some(0))
 603            .collect_vec();
 604        self.foreground_executor().spawn(async move {
 605            let credentials = CREDENTIALW {
 606                LastWritten: unsafe { GetSystemTimeAsFileTime() },
 607                Flags: CRED_FLAGS(0),
 608                Type: CRED_TYPE_GENERIC,
 609                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
 610                CredentialBlobSize: password.len() as u32,
 611                CredentialBlob: password.as_ptr() as *mut _,
 612                Persist: CRED_PERSIST_LOCAL_MACHINE,
 613                UserName: PWSTR::from_raw(username.as_mut_ptr()),
 614                ..CREDENTIALW::default()
 615            };
 616            unsafe { CredWriteW(&credentials, 0) }?;
 617            Ok(())
 618        })
 619    }
 620
 621    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
 622        let mut target_name = windows_credentials_target_name(url)
 623            .encode_utf16()
 624            .chain(Some(0))
 625            .collect_vec();
 626        self.foreground_executor().spawn(async move {
 627            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
 628            unsafe {
 629                CredReadW(
 630                    PCWSTR::from_raw(target_name.as_ptr()),
 631                    CRED_TYPE_GENERIC,
 632                    None,
 633                    &mut credentials,
 634                )?
 635            };
 636
 637            if credentials.is_null() {
 638                Ok(None)
 639            } else {
 640                let username: String = unsafe { (*credentials).UserName.to_string()? };
 641                let credential_blob = unsafe {
 642                    std::slice::from_raw_parts(
 643                        (*credentials).CredentialBlob,
 644                        (*credentials).CredentialBlobSize as usize,
 645                    )
 646                };
 647                let password = credential_blob.to_vec();
 648                unsafe { CredFree(credentials as *const _ as _) };
 649                Ok(Some((username, password)))
 650            }
 651        })
 652    }
 653
 654    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
 655        let mut target_name = windows_credentials_target_name(url)
 656            .encode_utf16()
 657            .chain(Some(0))
 658            .collect_vec();
 659        self.foreground_executor().spawn(async move {
 660            unsafe {
 661                CredDeleteW(
 662                    PCWSTR::from_raw(target_name.as_ptr()),
 663                    CRED_TYPE_GENERIC,
 664                    None,
 665                )?
 666            };
 667            Ok(())
 668        })
 669    }
 670
 671    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
 672        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
 673    }
 674
 675    fn perform_dock_menu_action(&self, action: usize) {
 676        unsafe {
 677            PostMessageW(
 678                Some(self.handle),
 679                WM_GPUI_DOCK_MENU_ACTION,
 680                WPARAM(self.inner.validation_number),
 681                LPARAM(action as isize),
 682            )
 683            .log_err();
 684        }
 685    }
 686
 687    fn update_jump_list(
 688        &self,
 689        menus: Vec<MenuItem>,
 690        entries: Vec<SmallVec<[PathBuf; 2]>>,
 691    ) -> Vec<SmallVec<[PathBuf; 2]>> {
 692        self.update_jump_list(menus, entries)
 693    }
 694}
 695
 696impl WindowsPlatformInner {
 697    fn new(context: &mut PlatformWindowCreateContext) -> Result<Rc<Self>> {
 698        let state = RefCell::new(WindowsPlatformState::new(
 699            context.directx_devices.take().unwrap(),
 700        ));
 701        Ok(Rc::new(Self {
 702            state,
 703            raw_window_handles: context.raw_window_handles.clone(),
 704            dispatcher: context.dispatcher.as_ref().unwrap().clone(),
 705            validation_number: context.validation_number,
 706            main_receiver: context.main_receiver.take().unwrap(),
 707        }))
 708    }
 709
 710    fn handle_msg(
 711        self: &Rc<Self>,
 712        handle: HWND,
 713        msg: u32,
 714        wparam: WPARAM,
 715        lparam: LPARAM,
 716    ) -> LRESULT {
 717        let handled = match msg {
 718            WM_GPUI_CLOSE_ONE_WINDOW
 719            | WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD
 720            | WM_GPUI_DOCK_MENU_ACTION
 721            | WM_GPUI_KEYBOARD_LAYOUT_CHANGED
 722            | WM_GPUI_GPU_DEVICE_LOST => self.handle_gpui_events(msg, wparam, lparam),
 723            _ => None,
 724        };
 725        if let Some(result) = handled {
 726            LRESULT(result)
 727        } else {
 728            unsafe { DefWindowProcW(handle, msg, wparam, lparam) }
 729        }
 730    }
 731
 732    fn handle_gpui_events(&self, message: u32, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
 733        if wparam.0 != self.validation_number {
 734            log::error!("Wrong validation number while processing message: {message}");
 735            return None;
 736        }
 737        match message {
 738            WM_GPUI_CLOSE_ONE_WINDOW => {
 739                if self.close_one_window(HWND(lparam.0 as _)) {
 740                    unsafe { PostQuitMessage(0) };
 741                }
 742                Some(0)
 743            }
 744            WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD => self.run_foreground_task(),
 745            WM_GPUI_DOCK_MENU_ACTION => self.handle_dock_action_event(lparam.0 as _),
 746            WM_GPUI_KEYBOARD_LAYOUT_CHANGED => self.handle_keyboard_layout_change(),
 747            WM_GPUI_GPU_DEVICE_LOST => self.handle_device_lost(lparam),
 748            _ => unreachable!(),
 749        }
 750    }
 751
 752    fn close_one_window(&self, target_window: HWND) -> bool {
 753        let Some(all_windows) = self.raw_window_handles.upgrade() else {
 754            log::error!("Failed to upgrade raw window handles");
 755            return false;
 756        };
 757        let mut lock = all_windows.write();
 758        let index = lock
 759            .iter()
 760            .position(|handle| handle.as_raw() == target_window)
 761            .unwrap();
 762        lock.remove(index);
 763
 764        lock.is_empty()
 765    }
 766
 767    #[inline]
 768    fn run_foreground_task(&self) -> Option<isize> {
 769        loop {
 770            for runnable in self.main_receiver.drain() {
 771                runnable.run();
 772            }
 773
 774            // Someone could enqueue a Runnable here. The flag is still true, so they will not PostMessage.
 775            // We need to check for those Runnables after we clear the flag.
 776            let dispatcher = self.dispatcher.clone();
 777
 778            dispatcher.wake_posted.store(false, Ordering::Release);
 779            match self.main_receiver.try_recv() {
 780                Ok(runnable) => {
 781                    let _ = dispatcher.wake_posted.swap(true, Ordering::AcqRel);
 782                    runnable.run();
 783                    continue;
 784                }
 785                _ => {
 786                    break;
 787                }
 788            }
 789        }
 790
 791        Some(0)
 792    }
 793
 794    fn handle_dock_action_event(&self, action_idx: usize) -> Option<isize> {
 795        let mut lock = self.state.borrow_mut();
 796        let mut callback = lock.callbacks.app_menu_action.take()?;
 797        let Some(action) = lock
 798            .jump_list
 799            .dock_menus
 800            .get(action_idx)
 801            .map(|dock_menu| dock_menu.action.boxed_clone())
 802        else {
 803            lock.callbacks.app_menu_action = Some(callback);
 804            log::error!("Dock menu for index {action_idx} not found");
 805            return Some(1);
 806        };
 807        drop(lock);
 808        callback(&*action);
 809        self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
 810        Some(0)
 811    }
 812
 813    fn handle_keyboard_layout_change(&self) -> Option<isize> {
 814        let mut callback = self
 815            .state
 816            .borrow_mut()
 817            .callbacks
 818            .keyboard_layout_change
 819            .take()?;
 820        callback();
 821        self.state.borrow_mut().callbacks.keyboard_layout_change = Some(callback);
 822        Some(0)
 823    }
 824
 825    fn handle_device_lost(&self, lparam: LPARAM) -> Option<isize> {
 826        let mut lock = self.state.borrow_mut();
 827        let directx_devices = lparam.0 as *const DirectXDevices;
 828        let directx_devices = unsafe { &*directx_devices };
 829        unsafe {
 830            ManuallyDrop::drop(&mut lock.directx_devices);
 831        }
 832        lock.directx_devices = ManuallyDrop::new(directx_devices.clone());
 833
 834        Some(0)
 835    }
 836}
 837
 838impl Drop for WindowsPlatform {
 839    fn drop(&mut self) {
 840        unsafe {
 841            DestroyWindow(self.handle)
 842                .context("Destroying platform window")
 843                .log_err();
 844            OleUninitialize();
 845        }
 846    }
 847}
 848
 849impl Drop for WindowsPlatformState {
 850    fn drop(&mut self) {
 851        unsafe {
 852            ManuallyDrop::drop(&mut self.directx_devices);
 853        }
 854    }
 855}
 856
 857pub(crate) struct WindowCreationInfo {
 858    pub(crate) icon: HICON,
 859    pub(crate) executor: ForegroundExecutor,
 860    pub(crate) current_cursor: Option<HCURSOR>,
 861    pub(crate) windows_version: WindowsVersion,
 862    pub(crate) drop_target_helper: IDropTargetHelper,
 863    pub(crate) validation_number: usize,
 864    pub(crate) main_receiver: flume::Receiver<Runnable>,
 865    pub(crate) platform_window_handle: HWND,
 866    pub(crate) disable_direct_composition: bool,
 867    pub(crate) directx_devices: DirectXDevices,
 868}
 869
 870struct PlatformWindowCreateContext {
 871    inner: Option<Result<Rc<WindowsPlatformInner>>>,
 872    raw_window_handles: std::sync::Weak<RwLock<SmallVec<[SafeHwnd; 4]>>>,
 873    validation_number: usize,
 874    main_sender: Option<flume::Sender<Runnable>>,
 875    main_receiver: Option<flume::Receiver<Runnable>>,
 876    directx_devices: Option<DirectXDevices>,
 877    dispatcher: Option<Arc<WindowsDispatcher>>,
 878}
 879
 880fn open_target(target: impl AsRef<OsStr>) -> Result<()> {
 881    let target = target.as_ref();
 882    let ret = unsafe {
 883        ShellExecuteW(
 884            None,
 885            windows::core::w!("open"),
 886            &HSTRING::from(target),
 887            None,
 888            None,
 889            SW_SHOWDEFAULT,
 890        )
 891    };
 892    if ret.0 as isize <= 32 {
 893        Err(anyhow::anyhow!(
 894            "Unable to open target: {}",
 895            std::io::Error::last_os_error()
 896        ))
 897    } else {
 898        Ok(())
 899    }
 900}
 901
 902fn open_target_in_explorer(target: &Path) -> Result<()> {
 903    let dir = target.parent().context("No parent folder found")?;
 904    let desktop = unsafe { SHGetDesktopFolder()? };
 905
 906    let mut dir_item = std::ptr::null_mut();
 907    unsafe {
 908        desktop.ParseDisplayName(
 909            HWND::default(),
 910            None,
 911            &HSTRING::from(dir),
 912            None,
 913            &mut dir_item,
 914            std::ptr::null_mut(),
 915        )?;
 916    }
 917
 918    let mut file_item = std::ptr::null_mut();
 919    unsafe {
 920        desktop.ParseDisplayName(
 921            HWND::default(),
 922            None,
 923            &HSTRING::from(target),
 924            None,
 925            &mut file_item,
 926            std::ptr::null_mut(),
 927        )?;
 928    }
 929
 930    let highlight = [file_item as *const _];
 931    unsafe { SHOpenFolderAndSelectItems(dir_item as _, Some(&highlight), 0) }.or_else(|err| {
 932        if err.code().0 == ERROR_FILE_NOT_FOUND.0 as i32 {
 933            // On some systems, the above call mysteriously fails with "file not
 934            // found" even though the file is there.  In these cases, ShellExecute()
 935            // seems to work as a fallback (although it won't select the file).
 936            open_target(dir).context("Opening target parent folder")
 937        } else {
 938            Err(anyhow::anyhow!("Can not open target path: {}", err))
 939        }
 940    })
 941}
 942
 943fn file_open_dialog(
 944    options: PathPromptOptions,
 945    window: Option<HWND>,
 946) -> Result<Option<Vec<PathBuf>>> {
 947    let folder_dialog: IFileOpenDialog =
 948        unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? };
 949
 950    let mut dialog_options = FOS_FILEMUSTEXIST;
 951    if options.multiple {
 952        dialog_options |= FOS_ALLOWMULTISELECT;
 953    }
 954    if options.directories {
 955        dialog_options |= FOS_PICKFOLDERS;
 956    }
 957
 958    unsafe {
 959        folder_dialog.SetOptions(dialog_options)?;
 960
 961        if let Some(prompt) = options.prompt {
 962            let prompt: &str = &prompt;
 963            folder_dialog.SetOkButtonLabel(&HSTRING::from(prompt))?;
 964        }
 965
 966        if folder_dialog.Show(window).is_err() {
 967            // User cancelled
 968            return Ok(None);
 969        }
 970    }
 971
 972    let results = unsafe { folder_dialog.GetResults()? };
 973    let file_count = unsafe { results.GetCount()? };
 974    if file_count == 0 {
 975        return Ok(None);
 976    }
 977
 978    let mut paths = Vec::with_capacity(file_count as usize);
 979    for i in 0..file_count {
 980        let item = unsafe { results.GetItemAt(i)? };
 981        let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };
 982        paths.push(PathBuf::from(path));
 983    }
 984
 985    Ok(Some(paths))
 986}
 987
 988fn file_save_dialog(
 989    directory: PathBuf,
 990    suggested_name: Option<String>,
 991    window: Option<HWND>,
 992) -> Result<Option<PathBuf>> {
 993    let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };
 994    if !directory.to_string_lossy().is_empty()
 995        && let Some(full_path) = directory
 996            .canonicalize()
 997            .context("failed to canonicalize directory")
 998            .log_err()
 999    {
1000        let full_path = SanitizedPath::new(&full_path);
1001        let full_path_string = full_path.to_string();
1002        let path_item: IShellItem =
1003            unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_string), None)? };
1004        unsafe {
1005            dialog
1006                .SetFolder(&path_item)
1007                .context("failed to set dialog folder")
1008                .log_err()
1009        };
1010    }
1011
1012    if let Some(suggested_name) = suggested_name {
1013        unsafe {
1014            dialog
1015                .SetFileName(&HSTRING::from(suggested_name))
1016                .context("failed to set file name")
1017                .log_err()
1018        };
1019    }
1020
1021    unsafe {
1022        dialog.SetFileTypes(&[Common::COMDLG_FILTERSPEC {
1023            pszName: windows::core::w!("All files"),
1024            pszSpec: windows::core::w!("*.*"),
1025        }])?;
1026        if dialog.Show(window).is_err() {
1027            // User cancelled
1028            return Ok(None);
1029        }
1030    }
1031    let shell_item = unsafe { dialog.GetResult()? };
1032    let file_path_string = unsafe {
1033        let pwstr = shell_item.GetDisplayName(SIGDN_FILESYSPATH)?;
1034        let string = pwstr.to_string()?;
1035        CoTaskMemFree(Some(pwstr.0 as _));
1036        string
1037    };
1038    Ok(Some(PathBuf::from(file_path_string)))
1039}
1040
1041fn load_icon() -> Result<HICON> {
1042    let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
1043    let handle = unsafe {
1044        LoadImageW(
1045            Some(module.into()),
1046            windows::core::PCWSTR(1 as _),
1047            IMAGE_ICON,
1048            0,
1049            0,
1050            LR_DEFAULTSIZE | LR_SHARED,
1051        )
1052        .context("unable to load icon file")?
1053    };
1054    Ok(HICON(handle.0))
1055}
1056
1057#[inline]
1058fn should_auto_hide_scrollbars() -> Result<bool> {
1059    let ui_settings = UISettings::new()?;
1060    Ok(ui_settings.AutoHideScrollBars()?)
1061}
1062
1063fn check_device_lost(device: &ID3D11Device) -> bool {
1064    let device_state = unsafe { device.GetDeviceRemovedReason() };
1065    match device_state {
1066        Ok(_) => false,
1067        Err(err) => {
1068            log::error!("DirectX device lost detected: {:?}", err);
1069            true
1070        }
1071    }
1072}
1073
1074fn handle_gpu_device_lost(
1075    directx_devices: &mut DirectXDevices,
1076    platform_window: HWND,
1077    validation_number: usize,
1078    all_windows: &std::sync::Weak<RwLock<SmallVec<[SafeHwnd; 4]>>>,
1079    text_system: &std::sync::Weak<DirectWriteTextSystem>,
1080) {
1081    // Here we wait a bit to ensure the system has time to recover from the device lost state.
1082    // If we don't wait, the final drawing result will be blank.
1083    std::thread::sleep(std::time::Duration::from_millis(350));
1084
1085    try_to_recover_from_device_lost(
1086        || {
1087            DirectXDevices::new()
1088                .context("Failed to recreate new DirectX devices after device lost")
1089        },
1090        |new_devices| *directx_devices = new_devices,
1091        || {
1092            log::error!("Failed to recover DirectX devices after multiple attempts.");
1093            // Do something here?
1094            // At this point, the device loss is considered unrecoverable.
1095            // std::process::exit(1);
1096        },
1097    );
1098    log::info!("DirectX devices successfully recreated.");
1099
1100    unsafe {
1101        SendMessageW(
1102            platform_window,
1103            WM_GPUI_GPU_DEVICE_LOST,
1104            Some(WPARAM(validation_number)),
1105            Some(LPARAM(directx_devices as *const _ as _)),
1106        );
1107    }
1108
1109    if let Some(text_system) = text_system.upgrade() {
1110        text_system.handle_gpu_lost(&directx_devices);
1111    }
1112    if let Some(all_windows) = all_windows.upgrade() {
1113        for window in all_windows.read().iter() {
1114            unsafe {
1115                SendMessageW(
1116                    window.as_raw(),
1117                    WM_GPUI_GPU_DEVICE_LOST,
1118                    Some(WPARAM(validation_number)),
1119                    Some(LPARAM(directx_devices as *const _ as _)),
1120                );
1121            }
1122        }
1123        std::thread::sleep(std::time::Duration::from_millis(200));
1124        for window in all_windows.read().iter() {
1125            unsafe {
1126                SendMessageW(
1127                    window.as_raw(),
1128                    WM_GPUI_FORCE_UPDATE_WINDOW,
1129                    Some(WPARAM(validation_number)),
1130                    None,
1131                );
1132            }
1133        }
1134    }
1135}
1136
1137const PLATFORM_WINDOW_CLASS_NAME: PCWSTR = w!("Zed::PlatformWindow");
1138
1139fn register_platform_window_class() {
1140    let wc = WNDCLASSW {
1141        lpfnWndProc: Some(window_procedure),
1142        lpszClassName: PCWSTR(PLATFORM_WINDOW_CLASS_NAME.as_ptr()),
1143        ..Default::default()
1144    };
1145    unsafe { RegisterClassW(&wc) };
1146}
1147
1148unsafe extern "system" fn window_procedure(
1149    hwnd: HWND,
1150    msg: u32,
1151    wparam: WPARAM,
1152    lparam: LPARAM,
1153) -> LRESULT {
1154    if msg == WM_NCCREATE {
1155        let params = lparam.0 as *const CREATESTRUCTW;
1156        let params = unsafe { &*params };
1157        let creation_context = params.lpCreateParams as *mut PlatformWindowCreateContext;
1158        let creation_context = unsafe { &mut *creation_context };
1159
1160        creation_context.dispatcher = Some(Arc::new(WindowsDispatcher::new(
1161            creation_context.main_sender.take().unwrap(),
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}