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