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