1use std::{
2 cell::RefCell,
3 mem::ManuallyDrop,
4 path::{Path, PathBuf},
5 rc::Rc,
6 sync::Arc,
7};
8
9use ::util::{paths::SanitizedPath, ResultExt};
10use anyhow::{anyhow, Context, Result};
11use async_task::Runnable;
12use futures::channel::oneshot::{self, Receiver};
13use itertools::Itertools;
14use parking_lot::RwLock;
15use smallvec::SmallVec;
16use windows::{
17 core::*,
18 Win32::{
19 Foundation::*,
20 Graphics::{
21 Gdi::*,
22 Imaging::{CLSID_WICImagingFactory, IWICImagingFactory},
23 },
24 Security::Credentials::*,
25 System::{Com::*, LibraryLoader::*, Ole::*, SystemInformation::*, Threading::*},
26 UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
27 },
28 UI::ViewManagement::UISettings,
29};
30
31use crate::*;
32
33pub(crate) struct WindowsPlatform {
34 state: RefCell<WindowsPlatformState>,
35 raw_window_handles: RwLock<SmallVec<[HWND; 4]>>,
36 // The below members will never change throughout the entire lifecycle of the app.
37 icon: HICON,
38 main_receiver: flume::Receiver<Runnable>,
39 dispatch_event: HANDLE,
40 background_executor: BackgroundExecutor,
41 foreground_executor: ForegroundExecutor,
42 text_system: Arc<DirectWriteTextSystem>,
43 windows_version: WindowsVersion,
44 bitmap_factory: ManuallyDrop<IWICImagingFactory>,
45 validation_number: usize,
46}
47
48pub(crate) struct WindowsPlatformState {
49 callbacks: PlatformCallbacks,
50 // NOTE: standard cursor handles don't need to close.
51 pub(crate) current_cursor: HCURSOR,
52}
53
54#[derive(Default)]
55struct PlatformCallbacks {
56 open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
57 quit: Option<Box<dyn FnMut()>>,
58 reopen: Option<Box<dyn FnMut()>>,
59 app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
60 will_open_app_menu: Option<Box<dyn FnMut()>>,
61 validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
62}
63
64impl WindowsPlatformState {
65 fn new() -> Self {
66 let callbacks = PlatformCallbacks::default();
67 let current_cursor = load_cursor(CursorStyle::Arrow);
68
69 Self {
70 callbacks,
71 current_cursor,
72 }
73 }
74}
75
76impl WindowsPlatform {
77 pub(crate) fn new() -> Self {
78 unsafe {
79 OleInitialize(None).expect("unable to initialize Windows OLE");
80 }
81 let (main_sender, main_receiver) = flume::unbounded::<Runnable>();
82 let dispatch_event = unsafe { CreateEventW(None, false, false, None) }.unwrap();
83 let dispatcher = Arc::new(WindowsDispatcher::new(main_sender, dispatch_event));
84 let background_executor = BackgroundExecutor::new(dispatcher.clone());
85 let foreground_executor = ForegroundExecutor::new(dispatcher);
86 let bitmap_factory = ManuallyDrop::new(unsafe {
87 CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)
88 .expect("Error creating bitmap factory.")
89 });
90 let text_system = Arc::new(
91 DirectWriteTextSystem::new(&bitmap_factory)
92 .expect("Error creating DirectWriteTextSystem"),
93 );
94 let icon = load_icon().unwrap_or_default();
95 let state = RefCell::new(WindowsPlatformState::new());
96 let raw_window_handles = RwLock::new(SmallVec::new());
97 let windows_version = WindowsVersion::new().expect("Error retrieve windows version");
98 let validation_number = rand::random::<usize>();
99
100 Self {
101 state,
102 raw_window_handles,
103 icon,
104 main_receiver,
105 dispatch_event,
106 background_executor,
107 foreground_executor,
108 text_system,
109 windows_version,
110 bitmap_factory,
111 validation_number,
112 }
113 }
114
115 fn redraw_all(&self) {
116 for handle in self.raw_window_handles.read().iter() {
117 unsafe {
118 RedrawWindow(
119 *handle,
120 None,
121 HRGN::default(),
122 RDW_INVALIDATE | RDW_UPDATENOW,
123 )
124 .ok()
125 .log_err();
126 }
127 }
128 }
129
130 pub fn try_get_windows_inner_from_hwnd(&self, hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
131 self.raw_window_handles
132 .read()
133 .iter()
134 .find(|entry| *entry == &hwnd)
135 .and_then(|hwnd| try_get_window_inner(*hwnd))
136 }
137
138 #[inline]
139 fn post_message(&self, message: u32, wparam: WPARAM, lparam: LPARAM) {
140 self.raw_window_handles
141 .read()
142 .iter()
143 .for_each(|handle| unsafe {
144 PostMessageW(*handle, message, wparam, lparam).log_err();
145 });
146 }
147
148 fn close_one_window(
149 &self,
150 target_window: HWND,
151 validation_number: usize,
152 msg: *const MSG,
153 ) -> bool {
154 if validation_number != self.validation_number {
155 unsafe { DispatchMessageW(msg) };
156 return false;
157 }
158 let mut lock = self.raw_window_handles.write();
159 let index = lock
160 .iter()
161 .position(|handle| *handle == target_window)
162 .unwrap();
163 lock.remove(index);
164
165 lock.is_empty()
166 }
167
168 #[inline]
169 fn run_foreground_tasks(&self) {
170 for runnable in self.main_receiver.drain() {
171 runnable.run();
172 }
173 }
174
175 fn generate_creation_info(&self) -> WindowCreationInfo {
176 WindowCreationInfo {
177 icon: self.icon,
178 executor: self.foreground_executor.clone(),
179 current_cursor: self.state.borrow().current_cursor,
180 windows_version: self.windows_version,
181 validation_number: self.validation_number,
182 main_receiver: self.main_receiver.clone(),
183 }
184 }
185}
186
187impl Platform for WindowsPlatform {
188 fn background_executor(&self) -> BackgroundExecutor {
189 self.background_executor.clone()
190 }
191
192 fn foreground_executor(&self) -> ForegroundExecutor {
193 self.foreground_executor.clone()
194 }
195
196 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
197 self.text_system.clone()
198 }
199
200 fn keyboard_layout(&self) -> String {
201 "unknown".into()
202 }
203
204 fn on_keyboard_layout_change(&self, _callback: Box<dyn FnMut()>) {
205 // todo(windows)
206 }
207
208 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
209 on_finish_launching();
210 let vsync_event = unsafe { Owned::new(CreateEventW(None, false, false, None).unwrap()) };
211 begin_vsync(*vsync_event);
212 'a: loop {
213 let wait_result = unsafe {
214 MsgWaitForMultipleObjects(
215 Some(&[*vsync_event, self.dispatch_event]),
216 false,
217 INFINITE,
218 QS_ALLINPUT,
219 )
220 };
221
222 match wait_result {
223 // compositor clock ticked so we should draw a frame
224 WAIT_EVENT(0) => self.redraw_all(),
225 // foreground tasks are dispatched
226 WAIT_EVENT(1) => self.run_foreground_tasks(),
227 // Windows thread messages are posted
228 WAIT_EVENT(2) => {
229 let mut msg = MSG::default();
230 unsafe {
231 while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
232 match msg.message {
233 WM_QUIT => break 'a,
234 CLOSE_ONE_WINDOW => {
235 if self.close_one_window(
236 HWND(msg.lParam.0 as _),
237 msg.wParam.0,
238 &msg,
239 ) {
240 break 'a;
241 }
242 }
243 _ => {
244 // todo(windows)
245 // crate `windows 0.56` reports true as Err
246 TranslateMessage(&msg).as_bool();
247 DispatchMessageW(&msg);
248 }
249 }
250 }
251 }
252 // foreground tasks may have been queued in the message handlers
253 self.run_foreground_tasks();
254 }
255 _ => {
256 log::error!("Something went wrong while waiting {:?}", wait_result);
257 break;
258 }
259 }
260 }
261
262 if let Some(ref mut callback) = self.state.borrow_mut().callbacks.quit {
263 callback();
264 }
265 }
266
267 fn quit(&self) {
268 self.foreground_executor()
269 .spawn(async { unsafe { PostQuitMessage(0) } })
270 .detach();
271 }
272
273 fn restart(&self, _: Option<PathBuf>) {
274 let pid = std::process::id();
275 let Some(app_path) = self.app_path().log_err() else {
276 return;
277 };
278 let script = format!(
279 r#"
280 $pidToWaitFor = {}
281 $exePath = "{}"
282
283 while ($true) {{
284 $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
285 if (-not $process) {{
286 Start-Process -FilePath $exePath
287 break
288 }}
289 Start-Sleep -Seconds 0.1
290 }}
291 "#,
292 pid,
293 app_path.display(),
294 );
295 let restart_process = util::command::new_std_command("powershell.exe")
296 .arg("-command")
297 .arg(script)
298 .spawn();
299
300 match restart_process {
301 Ok(_) => self.quit(),
302 Err(e) => log::error!("failed to spawn restart script: {:?}", e),
303 }
304 }
305
306 fn activate(&self, _ignoring_other_apps: bool) {}
307
308 fn hide(&self) {}
309
310 // todo(windows)
311 fn hide_other_apps(&self) {
312 unimplemented!()
313 }
314
315 // todo(windows)
316 fn unhide_other_apps(&self) {
317 unimplemented!()
318 }
319
320 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
321 WindowsDisplay::displays()
322 }
323
324 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
325 WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
326 }
327
328 fn screen_capture_sources(
329 &self,
330 ) -> oneshot::Receiver<Result<Vec<Box<dyn ScreenCaptureSource>>>> {
331 let (mut tx, rx) = oneshot::channel();
332 tx.send(Err(anyhow!("screen capture not implemented"))).ok();
333 rx
334 }
335
336 fn active_window(&self) -> Option<AnyWindowHandle> {
337 let active_window_hwnd = unsafe { GetActiveWindow() };
338 self.try_get_windows_inner_from_hwnd(active_window_hwnd)
339 .map(|inner| inner.handle)
340 }
341
342 fn open_window(
343 &self,
344 handle: AnyWindowHandle,
345 options: WindowParams,
346 ) -> Result<Box<dyn PlatformWindow>> {
347 let window = WindowsWindow::new(handle, options, self.generate_creation_info())?;
348 let handle = window.get_raw_handle();
349 self.raw_window_handles.write().push(handle);
350
351 Ok(Box::new(window))
352 }
353
354 fn window_appearance(&self) -> WindowAppearance {
355 system_appearance().log_err().unwrap_or_default()
356 }
357
358 fn open_url(&self, url: &str) {
359 let url_string = url.to_string();
360 self.background_executor()
361 .spawn(async move {
362 if url_string.is_empty() {
363 return;
364 }
365 open_target(url_string.as_str());
366 })
367 .detach();
368 }
369
370 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
371 self.state.borrow_mut().callbacks.open_urls = Some(callback);
372 }
373
374 fn prompt_for_paths(
375 &self,
376 options: PathPromptOptions,
377 ) -> Receiver<Result<Option<Vec<PathBuf>>>> {
378 let (tx, rx) = oneshot::channel();
379 self.foreground_executor()
380 .spawn(async move {
381 let _ = tx.send(file_open_dialog(options));
382 })
383 .detach();
384
385 rx
386 }
387
388 fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Result<Option<PathBuf>>> {
389 let directory = directory.to_owned();
390 let (tx, rx) = oneshot::channel();
391 self.foreground_executor()
392 .spawn(async move {
393 let _ = tx.send(file_save_dialog(directory));
394 })
395 .detach();
396
397 rx
398 }
399
400 fn reveal_path(&self, path: &Path) {
401 let Ok(file_full_path) = path.canonicalize() else {
402 log::error!("unable to parse file path");
403 return;
404 };
405 self.background_executor()
406 .spawn(async move {
407 let Some(path) = file_full_path.to_str() else {
408 return;
409 };
410 if path.is_empty() {
411 return;
412 }
413 open_target_in_explorer(path);
414 })
415 .detach();
416 }
417
418 fn open_with_system(&self, path: &Path) {
419 let Ok(full_path) = path.canonicalize() else {
420 log::error!("unable to parse file full path: {}", path.display());
421 return;
422 };
423 self.background_executor()
424 .spawn(async move {
425 let Some(full_path_str) = full_path.to_str() else {
426 return;
427 };
428 if full_path_str.is_empty() {
429 return;
430 };
431 open_target(full_path_str);
432 })
433 .detach();
434 }
435
436 fn on_quit(&self, callback: Box<dyn FnMut()>) {
437 self.state.borrow_mut().callbacks.quit = Some(callback);
438 }
439
440 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
441 self.state.borrow_mut().callbacks.reopen = Some(callback);
442 }
443
444 // todo(windows)
445 fn set_menus(&self, _menus: Vec<Menu>, _keymap: &Keymap) {}
446 fn set_dock_menu(&self, _menus: Vec<MenuItem>, _keymap: &Keymap) {}
447
448 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
449 self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
450 }
451
452 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
453 self.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
454 }
455
456 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
457 self.state.borrow_mut().callbacks.validate_app_menu_command = Some(callback);
458 }
459
460 fn app_path(&self) -> Result<PathBuf> {
461 Ok(std::env::current_exe()?)
462 }
463
464 // todo(windows)
465 fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
466 Err(anyhow!("not yet implemented"))
467 }
468
469 fn set_cursor_style(&self, style: CursorStyle) {
470 let hcursor = load_cursor(style);
471 let mut lock = self.state.borrow_mut();
472 if lock.current_cursor.0 != hcursor.0 {
473 self.post_message(CURSOR_STYLE_CHANGED, WPARAM(0), LPARAM(hcursor.0 as isize));
474 lock.current_cursor = hcursor;
475 }
476 }
477
478 fn should_auto_hide_scrollbars(&self) -> bool {
479 should_auto_hide_scrollbars().log_err().unwrap_or(false)
480 }
481
482 fn write_to_clipboard(&self, item: ClipboardItem) {
483 write_to_clipboard(item);
484 }
485
486 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
487 read_from_clipboard()
488 }
489
490 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
491 let mut password = password.to_vec();
492 let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
493 let mut target_name = windows_credentials_target_name(url)
494 .encode_utf16()
495 .chain(Some(0))
496 .collect_vec();
497 self.foreground_executor().spawn(async move {
498 let credentials = CREDENTIALW {
499 LastWritten: unsafe { GetSystemTimeAsFileTime() },
500 Flags: CRED_FLAGS(0),
501 Type: CRED_TYPE_GENERIC,
502 TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
503 CredentialBlobSize: password.len() as u32,
504 CredentialBlob: password.as_ptr() as *mut _,
505 Persist: CRED_PERSIST_LOCAL_MACHINE,
506 UserName: PWSTR::from_raw(username.as_mut_ptr()),
507 ..CREDENTIALW::default()
508 };
509 unsafe { CredWriteW(&credentials, 0) }?;
510 Ok(())
511 })
512 }
513
514 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
515 let mut target_name = windows_credentials_target_name(url)
516 .encode_utf16()
517 .chain(Some(0))
518 .collect_vec();
519 self.foreground_executor().spawn(async move {
520 let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
521 unsafe {
522 CredReadW(
523 PCWSTR::from_raw(target_name.as_ptr()),
524 CRED_TYPE_GENERIC,
525 0,
526 &mut credentials,
527 )?
528 };
529
530 if credentials.is_null() {
531 Ok(None)
532 } else {
533 let username: String = unsafe { (*credentials).UserName.to_string()? };
534 let credential_blob = unsafe {
535 std::slice::from_raw_parts(
536 (*credentials).CredentialBlob,
537 (*credentials).CredentialBlobSize as usize,
538 )
539 };
540 let password = credential_blob.to_vec();
541 unsafe { CredFree(credentials as *const _ as _) };
542 Ok(Some((username, password)))
543 }
544 })
545 }
546
547 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
548 let mut target_name = windows_credentials_target_name(url)
549 .encode_utf16()
550 .chain(Some(0))
551 .collect_vec();
552 self.foreground_executor().spawn(async move {
553 unsafe { CredDeleteW(PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, 0)? };
554 Ok(())
555 })
556 }
557
558 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
559 Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
560 }
561}
562
563impl Drop for WindowsPlatform {
564 fn drop(&mut self) {
565 unsafe {
566 ManuallyDrop::drop(&mut self.bitmap_factory);
567 OleUninitialize();
568 }
569 }
570}
571
572pub(crate) struct WindowCreationInfo {
573 pub(crate) icon: HICON,
574 pub(crate) executor: ForegroundExecutor,
575 pub(crate) current_cursor: HCURSOR,
576 pub(crate) windows_version: WindowsVersion,
577 pub(crate) validation_number: usize,
578 pub(crate) main_receiver: flume::Receiver<Runnable>,
579}
580
581fn open_target(target: &str) {
582 unsafe {
583 let ret = ShellExecuteW(
584 None,
585 windows::core::w!("open"),
586 &HSTRING::from(target),
587 None,
588 None,
589 SW_SHOWDEFAULT,
590 );
591 if ret.0 as isize <= 32 {
592 log::error!("Unable to open target: {}", std::io::Error::last_os_error());
593 }
594 }
595}
596
597fn open_target_in_explorer(target: &str) {
598 unsafe {
599 let ret = ShellExecuteW(
600 None,
601 windows::core::w!("open"),
602 windows::core::w!("explorer.exe"),
603 &HSTRING::from(format!("/select,{}", target).as_str()),
604 None,
605 SW_SHOWDEFAULT,
606 );
607 if ret.0 as isize <= 32 {
608 log::error!(
609 "Unable to open target in explorer: {}",
610 std::io::Error::last_os_error()
611 );
612 }
613 }
614}
615
616fn file_open_dialog(options: PathPromptOptions) -> Result<Option<Vec<PathBuf>>> {
617 let folder_dialog: IFileOpenDialog =
618 unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? };
619
620 let mut dialog_options = FOS_FILEMUSTEXIST;
621 if options.multiple {
622 dialog_options |= FOS_ALLOWMULTISELECT;
623 }
624 if options.directories {
625 dialog_options |= FOS_PICKFOLDERS;
626 }
627
628 unsafe {
629 folder_dialog.SetOptions(dialog_options)?;
630 if folder_dialog.Show(None).is_err() {
631 // User cancelled
632 return Ok(None);
633 }
634 }
635
636 let results = unsafe { folder_dialog.GetResults()? };
637 let file_count = unsafe { results.GetCount()? };
638 if file_count == 0 {
639 return Ok(None);
640 }
641
642 let mut paths = Vec::new();
643 for i in 0..file_count {
644 let item = unsafe { results.GetItemAt(i)? };
645 let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };
646 paths.push(PathBuf::from(path));
647 }
648
649 Ok(Some(paths))
650}
651
652fn file_save_dialog(directory: PathBuf) -> Result<Option<PathBuf>> {
653 let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };
654 if !directory.to_string_lossy().is_empty() {
655 if let Some(full_path) = directory.canonicalize().log_err() {
656 let full_path = SanitizedPath::from(full_path);
657 let full_path_string = full_path.to_string();
658 let path_item: IShellItem =
659 unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_string), None)? };
660 unsafe { dialog.SetFolder(&path_item).log_err() };
661 }
662 }
663 unsafe {
664 dialog.SetFileTypes(&[Common::COMDLG_FILTERSPEC {
665 pszName: windows::core::w!("All files"),
666 pszSpec: windows::core::w!("*.*"),
667 }])?;
668 if dialog.Show(None).is_err() {
669 // User cancelled
670 return Ok(None);
671 }
672 }
673 let shell_item = unsafe { dialog.GetResult()? };
674 let file_path_string = unsafe {
675 let pwstr = shell_item.GetDisplayName(SIGDN_FILESYSPATH)?;
676 let string = pwstr.to_string()?;
677 CoTaskMemFree(Some(pwstr.0 as _));
678 string
679 };
680 Ok(Some(PathBuf::from(file_path_string)))
681}
682
683fn begin_vsync(vsync_event: HANDLE) {
684 let event: SafeHandle = vsync_event.into();
685 std::thread::spawn(move || unsafe {
686 loop {
687 windows::Win32::Graphics::Dwm::DwmFlush().log_err();
688 SetEvent(*event).log_err();
689 }
690 });
691}
692
693fn load_icon() -> Result<HICON> {
694 let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
695 let handle = unsafe {
696 LoadImageW(
697 module,
698 IDI_APPLICATION,
699 IMAGE_ICON,
700 0,
701 0,
702 LR_DEFAULTSIZE | LR_SHARED,
703 )
704 .context("unable to load icon file")?
705 };
706 Ok(HICON(handle.0))
707}
708
709#[inline]
710fn should_auto_hide_scrollbars() -> Result<bool> {
711 let ui_settings = UISettings::new()?;
712 Ok(ui_settings.AutoHideScrollBars()?)
713}
714
715#[cfg(test)]
716mod tests {
717 use crate::{ClipboardItem, Platform, WindowsPlatform};
718
719 #[test]
720 fn test_clipboard() {
721 let platform = WindowsPlatform::new();
722 let item = ClipboardItem::new_string("你好".to_string());
723 platform.write_to_clipboard(item.clone());
724 assert_eq!(platform.read_from_clipboard(), Some(item));
725
726 let item = ClipboardItem::new_string("12345".to_string());
727 platform.write_to_clipboard(item.clone());
728 assert_eq!(platform.read_from_clipboard(), Some(item));
729
730 let item = ClipboardItem::new_string_with_json_metadata("abcdef".to_string(), vec![3, 4]);
731 platform.write_to_clipboard(item.clone());
732 assert_eq!(platform.read_from_clipboard(), Some(item));
733 }
734}