platform.rs

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