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
300impl Platform for WindowsPlatform {
301 fn background_executor(&self) -> BackgroundExecutor {
302 self.background_executor.clone()
303 }
304
305 fn foreground_executor(&self) -> ForegroundExecutor {
306 self.foreground_executor.clone()
307 }
308
309 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
310 self.text_system.clone()
311 }
312
313 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
314 Box::new(
315 WindowsKeyboardLayout::new()
316 .log_err()
317 .unwrap_or(WindowsKeyboardLayout::unknown()),
318 )
319 }
320
321 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
322 self.state.borrow_mut().callbacks.keyboard_layout_change = Some(callback);
323 }
324
325 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
326 on_finish_launching();
327 let vsync_event = unsafe { Owned::new(CreateEventW(None, false, false, None).unwrap()) };
328 begin_vsync(*vsync_event);
329 'a: loop {
330 let wait_result = unsafe {
331 MsgWaitForMultipleObjects(Some(&[*vsync_event]), false, INFINITE, QS_ALLINPUT)
332 };
333
334 match wait_result {
335 // compositor clock ticked so we should draw a frame
336 WAIT_EVENT(0) => self.redraw_all(),
337 // Windows thread messages are posted
338 WAIT_EVENT(1) => {
339 if self.handle_events() {
340 break 'a;
341 }
342 }
343 _ => {
344 log::error!("Something went wrong while waiting {:?}", wait_result);
345 break;
346 }
347 }
348 }
349
350 if let Some(ref mut callback) = self.state.borrow_mut().callbacks.quit {
351 callback();
352 }
353 }
354
355 fn quit(&self) {
356 self.foreground_executor()
357 .spawn(async { unsafe { PostQuitMessage(0) } })
358 .detach();
359 }
360
361 fn restart(&self, _: Option<PathBuf>) {
362 let pid = std::process::id();
363 let Some(app_path) = self.app_path().log_err() else {
364 return;
365 };
366 let script = format!(
367 r#"
368 $pidToWaitFor = {}
369 $exePath = "{}"
370
371 while ($true) {{
372 $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
373 if (-not $process) {{
374 Start-Process -FilePath $exePath
375 break
376 }}
377 Start-Sleep -Seconds 0.1
378 }}
379 "#,
380 pid,
381 app_path.display(),
382 );
383 let restart_process = util::command::new_std_command("powershell.exe")
384 .arg("-command")
385 .arg(script)
386 .spawn();
387
388 match restart_process {
389 Ok(_) => self.quit(),
390 Err(e) => log::error!("failed to spawn restart script: {:?}", e),
391 }
392 }
393
394 fn activate(&self, _ignoring_other_apps: bool) {}
395
396 fn hide(&self) {}
397
398 // todo(windows)
399 fn hide_other_apps(&self) {
400 unimplemented!()
401 }
402
403 // todo(windows)
404 fn unhide_other_apps(&self) {
405 unimplemented!()
406 }
407
408 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
409 WindowsDisplay::displays()
410 }
411
412 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
413 WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
414 }
415
416 fn is_screen_capture_supported(&self) -> bool {
417 false
418 }
419
420 fn screen_capture_sources(
421 &self,
422 ) -> oneshot::Receiver<Result<Vec<Box<dyn ScreenCaptureSource>>>> {
423 let (mut tx, rx) = oneshot::channel();
424 tx.send(Err(anyhow!("screen capture not implemented"))).ok();
425 rx
426 }
427
428 fn active_window(&self) -> Option<AnyWindowHandle> {
429 let active_window_hwnd = unsafe { GetActiveWindow() };
430 self.try_get_windows_inner_from_hwnd(active_window_hwnd)
431 .map(|inner| inner.handle)
432 }
433
434 fn open_window(
435 &self,
436 handle: AnyWindowHandle,
437 options: WindowParams,
438 ) -> Result<Box<dyn PlatformWindow>> {
439 let window = WindowsWindow::new(
440 handle,
441 options,
442 self.generate_creation_info(),
443 &self.gpu_context,
444 )?;
445 let handle = window.get_raw_handle();
446 self.raw_window_handles.write().push(handle);
447
448 Ok(Box::new(window))
449 }
450
451 fn window_appearance(&self) -> WindowAppearance {
452 system_appearance().log_err().unwrap_or_default()
453 }
454
455 fn open_url(&self, url: &str) {
456 let url_string = url.to_string();
457 self.background_executor()
458 .spawn(async move {
459 if url_string.is_empty() {
460 return;
461 }
462 open_target(url_string.as_str());
463 })
464 .detach();
465 }
466
467 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
468 self.state.borrow_mut().callbacks.open_urls = Some(callback);
469 }
470
471 fn prompt_for_paths(
472 &self,
473 options: PathPromptOptions,
474 ) -> Receiver<Result<Option<Vec<PathBuf>>>> {
475 let (tx, rx) = oneshot::channel();
476 self.foreground_executor()
477 .spawn(async move {
478 let _ = tx.send(file_open_dialog(options));
479 })
480 .detach();
481
482 rx
483 }
484
485 fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Result<Option<PathBuf>>> {
486 let directory = directory.to_owned();
487 let (tx, rx) = oneshot::channel();
488 self.foreground_executor()
489 .spawn(async move {
490 let _ = tx.send(file_save_dialog(directory));
491 })
492 .detach();
493
494 rx
495 }
496
497 fn can_select_mixed_files_and_dirs(&self) -> bool {
498 // The FOS_PICKFOLDERS flag toggles between "only files" and "only folders".
499 false
500 }
501
502 fn reveal_path(&self, path: &Path) {
503 let Ok(file_full_path) = path.canonicalize() else {
504 log::error!("unable to parse file path");
505 return;
506 };
507 self.background_executor()
508 .spawn(async move {
509 let Some(path) = file_full_path.to_str() else {
510 return;
511 };
512 if path.is_empty() {
513 return;
514 }
515 open_target_in_explorer(path);
516 })
517 .detach();
518 }
519
520 fn open_with_system(&self, path: &Path) {
521 let Ok(full_path) = path.canonicalize() else {
522 log::error!("unable to parse file full path: {}", path.display());
523 return;
524 };
525 self.background_executor()
526 .spawn(async move {
527 let Some(full_path_str) = full_path.to_str() else {
528 return;
529 };
530 if full_path_str.is_empty() {
531 return;
532 };
533 open_target(full_path_str);
534 })
535 .detach();
536 }
537
538 fn on_quit(&self, callback: Box<dyn FnMut()>) {
539 self.state.borrow_mut().callbacks.quit = Some(callback);
540 }
541
542 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
543 self.state.borrow_mut().callbacks.reopen = Some(callback);
544 }
545
546 fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
547 self.state.borrow_mut().menus = menus.into_iter().map(|menu| menu.owned()).collect();
548 }
549
550 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
551 Some(self.state.borrow().menus.clone())
552 }
553
554 fn set_dock_menu(&self, menus: Vec<MenuItem>, _keymap: &Keymap) {
555 self.set_dock_menus(menus);
556 }
557
558 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
559 self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
560 }
561
562 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
563 self.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
564 }
565
566 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
567 self.state.borrow_mut().callbacks.validate_app_menu_command = Some(callback);
568 }
569
570 fn app_path(&self) -> Result<PathBuf> {
571 Ok(std::env::current_exe()?)
572 }
573
574 // todo(windows)
575 fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
576 anyhow::bail!("not yet implemented");
577 }
578
579 fn set_cursor_style(&self, style: CursorStyle) {
580 let hcursor = load_cursor(style);
581 let mut lock = self.state.borrow_mut();
582 if lock.current_cursor.map(|c| c.0) != hcursor.map(|c| c.0) {
583 self.post_message(
584 WM_GPUI_CURSOR_STYLE_CHANGED,
585 WPARAM(0),
586 LPARAM(hcursor.map_or(0, |c| c.0 as isize)),
587 );
588 lock.current_cursor = hcursor;
589 }
590 }
591
592 fn should_auto_hide_scrollbars(&self) -> bool {
593 should_auto_hide_scrollbars().log_err().unwrap_or(false)
594 }
595
596 fn write_to_clipboard(&self, item: ClipboardItem) {
597 write_to_clipboard(item);
598 }
599
600 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
601 read_from_clipboard()
602 }
603
604 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
605 let mut password = password.to_vec();
606 let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
607 let mut target_name = windows_credentials_target_name(url)
608 .encode_utf16()
609 .chain(Some(0))
610 .collect_vec();
611 self.foreground_executor().spawn(async move {
612 let credentials = CREDENTIALW {
613 LastWritten: unsafe { GetSystemTimeAsFileTime() },
614 Flags: CRED_FLAGS(0),
615 Type: CRED_TYPE_GENERIC,
616 TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
617 CredentialBlobSize: password.len() as u32,
618 CredentialBlob: password.as_ptr() as *mut _,
619 Persist: CRED_PERSIST_LOCAL_MACHINE,
620 UserName: PWSTR::from_raw(username.as_mut_ptr()),
621 ..CREDENTIALW::default()
622 };
623 unsafe { CredWriteW(&credentials, 0) }?;
624 Ok(())
625 })
626 }
627
628 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
629 let mut target_name = windows_credentials_target_name(url)
630 .encode_utf16()
631 .chain(Some(0))
632 .collect_vec();
633 self.foreground_executor().spawn(async move {
634 let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
635 unsafe {
636 CredReadW(
637 PCWSTR::from_raw(target_name.as_ptr()),
638 CRED_TYPE_GENERIC,
639 None,
640 &mut credentials,
641 )?
642 };
643
644 if credentials.is_null() {
645 Ok(None)
646 } else {
647 let username: String = unsafe { (*credentials).UserName.to_string()? };
648 let credential_blob = unsafe {
649 std::slice::from_raw_parts(
650 (*credentials).CredentialBlob,
651 (*credentials).CredentialBlobSize as usize,
652 )
653 };
654 let password = credential_blob.to_vec();
655 unsafe { CredFree(credentials as *const _ as _) };
656 Ok(Some((username, password)))
657 }
658 })
659 }
660
661 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
662 let mut target_name = windows_credentials_target_name(url)
663 .encode_utf16()
664 .chain(Some(0))
665 .collect_vec();
666 self.foreground_executor().spawn(async move {
667 unsafe {
668 CredDeleteW(
669 PCWSTR::from_raw(target_name.as_ptr()),
670 CRED_TYPE_GENERIC,
671 None,
672 )?
673 };
674 Ok(())
675 })
676 }
677
678 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
679 Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
680 }
681
682 fn perform_dock_menu_action(&self, action: usize) {
683 unsafe {
684 PostThreadMessageW(
685 self.main_thread_id_win32,
686 WM_GPUI_DOCK_MENU_ACTION,
687 WPARAM(self.validation_number),
688 LPARAM(action as isize),
689 )
690 .log_err();
691 }
692 }
693
694 fn update_jump_list(
695 &self,
696 menus: Vec<MenuItem>,
697 entries: Vec<SmallVec<[PathBuf; 2]>>,
698 ) -> Vec<SmallVec<[PathBuf; 2]>> {
699 self.update_jump_list(menus, entries)
700 }
701}
702
703impl Drop for WindowsPlatform {
704 fn drop(&mut self) {
705 unsafe {
706 ManuallyDrop::drop(&mut self.bitmap_factory);
707 OleUninitialize();
708 }
709 }
710}
711
712pub(crate) struct WindowCreationInfo {
713 pub(crate) icon: HICON,
714 pub(crate) executor: ForegroundExecutor,
715 pub(crate) current_cursor: Option<HCURSOR>,
716 pub(crate) windows_version: WindowsVersion,
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(options: PathPromptOptions) -> Result<Option<Vec<PathBuf>>> {
758 let folder_dialog: IFileOpenDialog =
759 unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? };
760
761 let mut dialog_options = FOS_FILEMUSTEXIST;
762 if options.multiple {
763 dialog_options |= FOS_ALLOWMULTISELECT;
764 }
765 if options.directories {
766 dialog_options |= FOS_PICKFOLDERS;
767 }
768
769 unsafe {
770 folder_dialog.SetOptions(dialog_options)?;
771 if folder_dialog.Show(None).is_err() {
772 // User cancelled
773 return Ok(None);
774 }
775 }
776
777 let results = unsafe { folder_dialog.GetResults()? };
778 let file_count = unsafe { results.GetCount()? };
779 if file_count == 0 {
780 return Ok(None);
781 }
782
783 let mut paths = Vec::with_capacity(file_count as usize);
784 for i in 0..file_count {
785 let item = unsafe { results.GetItemAt(i)? };
786 let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };
787 paths.push(PathBuf::from(path));
788 }
789
790 Ok(Some(paths))
791}
792
793fn file_save_dialog(directory: PathBuf) -> Result<Option<PathBuf>> {
794 let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };
795 if !directory.to_string_lossy().is_empty() {
796 if let Some(full_path) = directory.canonicalize().log_err() {
797 let full_path = SanitizedPath::from(full_path);
798 let full_path_string = full_path.to_string();
799 let path_item: IShellItem =
800 unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_string), None)? };
801 unsafe { dialog.SetFolder(&path_item).log_err() };
802 }
803 }
804 unsafe {
805 dialog.SetFileTypes(&[Common::COMDLG_FILTERSPEC {
806 pszName: windows::core::w!("All files"),
807 pszSpec: windows::core::w!("*.*"),
808 }])?;
809 if dialog.Show(None).is_err() {
810 // User cancelled
811 return Ok(None);
812 }
813 }
814 let shell_item = unsafe { dialog.GetResult()? };
815 let file_path_string = unsafe {
816 let pwstr = shell_item.GetDisplayName(SIGDN_FILESYSPATH)?;
817 let string = pwstr.to_string()?;
818 CoTaskMemFree(Some(pwstr.0 as _));
819 string
820 };
821 Ok(Some(PathBuf::from(file_path_string)))
822}
823
824fn begin_vsync(vsync_event: HANDLE) {
825 let event: SafeHandle = vsync_event.into();
826 std::thread::spawn(move || unsafe {
827 loop {
828 windows::Win32::Graphics::Dwm::DwmFlush().log_err();
829 SetEvent(*event).log_err();
830 }
831 });
832}
833
834fn load_icon() -> Result<HICON> {
835 let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
836 let handle = unsafe {
837 LoadImageW(
838 Some(module.into()),
839 windows::core::PCWSTR(1 as _),
840 IMAGE_ICON,
841 0,
842 0,
843 LR_DEFAULTSIZE | LR_SHARED,
844 )
845 .context("unable to load icon file")?
846 };
847 Ok(HICON(handle.0))
848}
849
850#[inline]
851fn should_auto_hide_scrollbars() -> Result<bool> {
852 let ui_settings = UISettings::new()?;
853 Ok(ui_settings.AutoHideScrollBars()?)
854}
855
856#[cfg(test)]
857mod tests {
858 use crate::{ClipboardItem, read_from_clipboard, write_to_clipboard};
859
860 #[test]
861 fn test_clipboard() {
862 let item = ClipboardItem::new_string("你好,我是张小白".to_string());
863 write_to_clipboard(item.clone());
864 assert_eq!(read_from_clipboard(), Some(item));
865
866 let item = ClipboardItem::new_string("12345".to_string());
867 write_to_clipboard(item.clone());
868 assert_eq!(read_from_clipboard(), Some(item));
869
870 let item = ClipboardItem::new_string_with_json_metadata("abcdef".to_string(), vec![3, 4]);
871 write_to_clipboard(item.clone());
872 assert_eq!(read_from_clipboard(), Some(item));
873 }
874}