platform.rs

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