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