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