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