platform.rs

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