platform.rs

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