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