1use std::{
2 cell::RefCell,
3 mem::ManuallyDrop,
4 path::{Path, PathBuf},
5 rc::Rc,
6 sync::Arc,
7};
8
9use ::util::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 run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
201 on_finish_launching();
202 let vsync_event = unsafe { Owned::new(CreateEventW(None, false, false, None).unwrap()) };
203 begin_vsync(*vsync_event);
204 'a: loop {
205 let wait_result = unsafe {
206 MsgWaitForMultipleObjects(
207 Some(&[*vsync_event, self.dispatch_event]),
208 false,
209 INFINITE,
210 QS_ALLINPUT,
211 )
212 };
213
214 match wait_result {
215 // compositor clock ticked so we should draw a frame
216 WAIT_EVENT(0) => self.redraw_all(),
217 // foreground tasks are dispatched
218 WAIT_EVENT(1) => self.run_foreground_tasks(),
219 // Windows thread messages are posted
220 WAIT_EVENT(2) => {
221 let mut msg = MSG::default();
222 unsafe {
223 while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
224 match msg.message {
225 WM_QUIT => break 'a,
226 CLOSE_ONE_WINDOW => {
227 if self.close_one_window(
228 HWND(msg.lParam.0 as _),
229 msg.wParam.0,
230 &msg,
231 ) {
232 break 'a;
233 }
234 }
235 _ => {
236 // todo(windows)
237 // crate `windows 0.56` reports true as Err
238 TranslateMessage(&msg).as_bool();
239 DispatchMessageW(&msg);
240 }
241 }
242 }
243 }
244 // foreground tasks may have been queued in the message handlers
245 self.run_foreground_tasks();
246 }
247 _ => {
248 log::error!("Something went wrong while waiting {:?}", wait_result);
249 break;
250 }
251 }
252 }
253
254 if let Some(ref mut callback) = self.state.borrow_mut().callbacks.quit {
255 callback();
256 }
257 }
258
259 fn quit(&self) {
260 self.foreground_executor()
261 .spawn(async { unsafe { PostQuitMessage(0) } })
262 .detach();
263 }
264
265 fn restart(&self, _: Option<PathBuf>) {
266 let pid = std::process::id();
267 let Some(app_path) = self.app_path().log_err() else {
268 return;
269 };
270 let script = format!(
271 r#"
272 $pidToWaitFor = {}
273 $exePath = "{}"
274
275 while ($true) {{
276 $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
277 if (-not $process) {{
278 Start-Process -FilePath $exePath
279 break
280 }}
281 Start-Sleep -Seconds 0.1
282 }}
283 "#,
284 pid,
285 app_path.display(),
286 );
287 let restart_process = std::process::Command::new("powershell.exe")
288 .arg("-command")
289 .arg(script)
290 .spawn();
291
292 match restart_process {
293 Ok(_) => self.quit(),
294 Err(e) => log::error!("failed to spawn restart script: {:?}", e),
295 }
296 }
297
298 // todo(windows)
299 fn activate(&self, _ignoring_other_apps: bool) {}
300
301 // todo(windows)
302 fn hide(&self) {
303 unimplemented!()
304 }
305
306 // todo(windows)
307 fn hide_other_apps(&self) {
308 unimplemented!()
309 }
310
311 // todo(windows)
312 fn unhide_other_apps(&self) {
313 unimplemented!()
314 }
315
316 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
317 WindowsDisplay::displays()
318 }
319
320 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
321 WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
322 }
323
324 fn active_window(&self) -> Option<AnyWindowHandle> {
325 let active_window_hwnd = unsafe { GetActiveWindow() };
326 self.try_get_windows_inner_from_hwnd(active_window_hwnd)
327 .map(|inner| inner.handle)
328 }
329
330 fn open_window(
331 &self,
332 handle: AnyWindowHandle,
333 options: WindowParams,
334 ) -> Result<Box<dyn PlatformWindow>> {
335 let window = WindowsWindow::new(handle, options, self.generate_creation_info())?;
336 let handle = window.get_raw_handle();
337 self.raw_window_handles.write().push(handle);
338
339 Ok(Box::new(window))
340 }
341
342 fn window_appearance(&self) -> WindowAppearance {
343 system_appearance().log_err().unwrap_or_default()
344 }
345
346 fn open_url(&self, url: &str) {
347 let url_string = url.to_string();
348 self.background_executor()
349 .spawn(async move {
350 if url_string.is_empty() {
351 return;
352 }
353 open_target(url_string.as_str());
354 })
355 .detach();
356 }
357
358 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
359 self.state.borrow_mut().callbacks.open_urls = Some(callback);
360 }
361
362 fn prompt_for_paths(
363 &self,
364 options: PathPromptOptions,
365 ) -> Receiver<Result<Option<Vec<PathBuf>>>> {
366 let (tx, rx) = oneshot::channel();
367 self.foreground_executor()
368 .spawn(async move {
369 let _ = tx.send(file_open_dialog(options));
370 })
371 .detach();
372
373 rx
374 }
375
376 fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Result<Option<PathBuf>>> {
377 let directory = directory.to_owned();
378 let (tx, rx) = oneshot::channel();
379 self.foreground_executor()
380 .spawn(async move {
381 let _ = tx.send(file_save_dialog(directory));
382 })
383 .detach();
384
385 rx
386 }
387
388 fn reveal_path(&self, path: &Path) {
389 let Ok(file_full_path) = path.canonicalize() else {
390 log::error!("unable to parse file path");
391 return;
392 };
393 self.background_executor()
394 .spawn(async move {
395 let Some(path) = file_full_path.to_str() else {
396 return;
397 };
398 if path.is_empty() {
399 return;
400 }
401 open_target_in_explorer(path);
402 })
403 .detach();
404 }
405
406 fn open_with_system(&self, path: &Path) {
407 let Ok(full_path) = path.canonicalize() else {
408 log::error!("unable to parse file full path: {}", path.display());
409 return;
410 };
411 self.background_executor()
412 .spawn(async move {
413 let Some(full_path_str) = full_path.to_str() else {
414 return;
415 };
416 if full_path_str.is_empty() {
417 return;
418 };
419 open_target(full_path_str);
420 })
421 .detach();
422 }
423
424 fn on_quit(&self, callback: Box<dyn FnMut()>) {
425 self.state.borrow_mut().callbacks.quit = Some(callback);
426 }
427
428 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
429 self.state.borrow_mut().callbacks.reopen = Some(callback);
430 }
431
432 // todo(windows)
433 fn set_menus(&self, _menus: Vec<Menu>, _keymap: &Keymap) {}
434 fn set_dock_menu(&self, _menus: Vec<MenuItem>, _keymap: &Keymap) {}
435
436 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
437 self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
438 }
439
440 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
441 self.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
442 }
443
444 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
445 self.state.borrow_mut().callbacks.validate_app_menu_command = Some(callback);
446 }
447
448 fn app_path(&self) -> Result<PathBuf> {
449 Ok(std::env::current_exe()?)
450 }
451
452 // todo(windows)
453 fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
454 Err(anyhow!("not yet implemented"))
455 }
456
457 fn set_cursor_style(&self, style: CursorStyle) {
458 let hcursor = load_cursor(style);
459 let mut lock = self.state.borrow_mut();
460 if lock.current_cursor.0 != hcursor.0 {
461 self.post_message(CURSOR_STYLE_CHANGED, WPARAM(0), LPARAM(hcursor.0 as isize));
462 lock.current_cursor = hcursor;
463 }
464 }
465
466 fn should_auto_hide_scrollbars(&self) -> bool {
467 should_auto_hide_scrollbars().log_err().unwrap_or(false)
468 }
469
470 fn write_to_clipboard(&self, item: ClipboardItem) {
471 write_to_clipboard(item);
472 }
473
474 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
475 read_from_clipboard()
476 }
477
478 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
479 let mut password = password.to_vec();
480 let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
481 let mut target_name = windows_credentials_target_name(url)
482 .encode_utf16()
483 .chain(Some(0))
484 .collect_vec();
485 self.foreground_executor().spawn(async move {
486 let credentials = CREDENTIALW {
487 LastWritten: unsafe { GetSystemTimeAsFileTime() },
488 Flags: CRED_FLAGS(0),
489 Type: CRED_TYPE_GENERIC,
490 TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
491 CredentialBlobSize: password.len() as u32,
492 CredentialBlob: password.as_ptr() as *mut _,
493 Persist: CRED_PERSIST_LOCAL_MACHINE,
494 UserName: PWSTR::from_raw(username.as_mut_ptr()),
495 ..CREDENTIALW::default()
496 };
497 unsafe { CredWriteW(&credentials, 0) }?;
498 Ok(())
499 })
500 }
501
502 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
503 let mut target_name = windows_credentials_target_name(url)
504 .encode_utf16()
505 .chain(Some(0))
506 .collect_vec();
507 self.foreground_executor().spawn(async move {
508 let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
509 unsafe {
510 CredReadW(
511 PCWSTR::from_raw(target_name.as_ptr()),
512 CRED_TYPE_GENERIC,
513 0,
514 &mut credentials,
515 )?
516 };
517
518 if credentials.is_null() {
519 Ok(None)
520 } else {
521 let username: String = unsafe { (*credentials).UserName.to_string()? };
522 let credential_blob = unsafe {
523 std::slice::from_raw_parts(
524 (*credentials).CredentialBlob,
525 (*credentials).CredentialBlobSize as usize,
526 )
527 };
528 let password = credential_blob.to_vec();
529 unsafe { CredFree(credentials as *const _ as _) };
530 Ok(Some((username, password)))
531 }
532 })
533 }
534
535 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
536 let mut target_name = windows_credentials_target_name(url)
537 .encode_utf16()
538 .chain(Some(0))
539 .collect_vec();
540 self.foreground_executor().spawn(async move {
541 unsafe { CredDeleteW(PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, 0)? };
542 Ok(())
543 })
544 }
545
546 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
547 Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
548 }
549}
550
551impl Drop for WindowsPlatform {
552 fn drop(&mut self) {
553 unsafe {
554 ManuallyDrop::drop(&mut self.bitmap_factory);
555 OleUninitialize();
556 }
557 }
558}
559
560pub(crate) struct WindowCreationInfo {
561 pub(crate) icon: HICON,
562 pub(crate) executor: ForegroundExecutor,
563 pub(crate) current_cursor: HCURSOR,
564 pub(crate) windows_version: WindowsVersion,
565 pub(crate) validation_number: usize,
566 pub(crate) main_receiver: flume::Receiver<Runnable>,
567}
568
569fn open_target(target: &str) {
570 unsafe {
571 let ret = ShellExecuteW(
572 None,
573 windows::core::w!("open"),
574 &HSTRING::from(target),
575 None,
576 None,
577 SW_SHOWDEFAULT,
578 );
579 if ret.0 as isize <= 32 {
580 log::error!("Unable to open target: {}", std::io::Error::last_os_error());
581 }
582 }
583}
584
585fn open_target_in_explorer(target: &str) {
586 unsafe {
587 let ret = ShellExecuteW(
588 None,
589 windows::core::w!("open"),
590 windows::core::w!("explorer.exe"),
591 &HSTRING::from(format!("/select,{}", target).as_str()),
592 None,
593 SW_SHOWDEFAULT,
594 );
595 if ret.0 as isize <= 32 {
596 log::error!(
597 "Unable to open target in explorer: {}",
598 std::io::Error::last_os_error()
599 );
600 }
601 }
602}
603
604fn file_open_dialog(options: PathPromptOptions) -> Result<Option<Vec<PathBuf>>> {
605 let folder_dialog: IFileOpenDialog =
606 unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? };
607
608 let mut dialog_options = FOS_FILEMUSTEXIST;
609 if options.multiple {
610 dialog_options |= FOS_ALLOWMULTISELECT;
611 }
612 if options.directories {
613 dialog_options |= FOS_PICKFOLDERS;
614 }
615
616 unsafe {
617 folder_dialog.SetOptions(dialog_options)?;
618 if folder_dialog.Show(None).is_err() {
619 // User cancelled
620 return Ok(None);
621 }
622 }
623
624 let results = unsafe { folder_dialog.GetResults()? };
625 let file_count = unsafe { results.GetCount()? };
626 if file_count == 0 {
627 return Ok(None);
628 }
629
630 let mut paths = Vec::new();
631 for i in 0..file_count {
632 let item = unsafe { results.GetItemAt(i)? };
633 let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };
634 paths.push(PathBuf::from(path));
635 }
636
637 Ok(Some(paths))
638}
639
640fn file_save_dialog(directory: PathBuf) -> Result<Option<PathBuf>> {
641 let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };
642 if !directory.to_string_lossy().is_empty() {
643 if let Some(full_path) = directory.canonicalize().log_err() {
644 let full_path = full_path.to_string_lossy();
645 let full_path_str = full_path.trim_start_matches("\\\\?\\");
646 if !full_path_str.is_empty() {
647 let path_item: IShellItem =
648 unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_str), None)? };
649 unsafe { dialog.SetFolder(&path_item).log_err() };
650 }
651 }
652 }
653 unsafe {
654 dialog.SetFileTypes(&[Common::COMDLG_FILTERSPEC {
655 pszName: windows::core::w!("All files"),
656 pszSpec: windows::core::w!("*.*"),
657 }])?;
658 if dialog.Show(None).is_err() {
659 // User cancelled
660 return Ok(None);
661 }
662 }
663 let shell_item = unsafe { dialog.GetResult()? };
664 let file_path_string = unsafe {
665 let pwstr = shell_item.GetDisplayName(SIGDN_FILESYSPATH)?;
666 let string = pwstr.to_string()?;
667 CoTaskMemFree(Some(pwstr.0 as _));
668 string
669 };
670 Ok(Some(PathBuf::from(file_path_string)))
671}
672
673fn begin_vsync(vsync_event: HANDLE) {
674 let event: SafeHandle = vsync_event.into();
675 std::thread::spawn(move || unsafe {
676 loop {
677 windows::Win32::Graphics::Dwm::DwmFlush().log_err();
678 SetEvent(*event).log_err();
679 }
680 });
681}
682
683fn load_icon() -> Result<HICON> {
684 let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
685 let handle = unsafe {
686 LoadImageW(
687 module,
688 IDI_APPLICATION,
689 IMAGE_ICON,
690 0,
691 0,
692 LR_DEFAULTSIZE | LR_SHARED,
693 )
694 .context("unable to load icon file")?
695 };
696 Ok(HICON(handle.0))
697}
698
699#[inline]
700fn should_auto_hide_scrollbars() -> Result<bool> {
701 let ui_settings = UISettings::new()?;
702 Ok(ui_settings.AutoHideScrollBars()?)
703}
704
705#[cfg(test)]
706mod tests {
707 use crate::{ClipboardItem, Platform, WindowsPlatform};
708
709 #[test]
710 fn test_clipboard() {
711 let platform = WindowsPlatform::new();
712 let item = ClipboardItem::new_string("你好".to_string());
713 platform.write_to_clipboard(item.clone());
714 assert_eq!(platform.read_from_clipboard(), Some(item));
715
716 let item = ClipboardItem::new_string("12345".to_string());
717 platform.write_to_clipboard(item.clone());
718 assert_eq!(platform.read_from_clipboard(), Some(item));
719
720 let item = ClipboardItem::new_string_with_json_metadata("abcdef".to_string(), vec![3, 4]);
721 platform.write_to_clipboard(item.clone());
722 assert_eq!(platform.read_from_clipboard(), Some(item));
723 }
724}