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