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