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