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