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