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