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