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