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