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