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