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 can_select_mixed_files_and_dirs(&self) -> bool {
411 // The FOS_PICKFOLDERS flag toggles between "only files" and "only folders".
412 false
413 }
414
415 fn reveal_path(&self, path: &Path) {
416 let Ok(file_full_path) = path.canonicalize() else {
417 log::error!("unable to parse file path");
418 return;
419 };
420 self.background_executor()
421 .spawn(async move {
422 let Some(path) = file_full_path.to_str() else {
423 return;
424 };
425 if path.is_empty() {
426 return;
427 }
428 open_target_in_explorer(path);
429 })
430 .detach();
431 }
432
433 fn open_with_system(&self, path: &Path) {
434 let Ok(full_path) = path.canonicalize() else {
435 log::error!("unable to parse file full path: {}", path.display());
436 return;
437 };
438 self.background_executor()
439 .spawn(async move {
440 let Some(full_path_str) = full_path.to_str() else {
441 return;
442 };
443 if full_path_str.is_empty() {
444 return;
445 };
446 open_target(full_path_str);
447 })
448 .detach();
449 }
450
451 fn on_quit(&self, callback: Box<dyn FnMut()>) {
452 self.state.borrow_mut().callbacks.quit = Some(callback);
453 }
454
455 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
456 self.state.borrow_mut().callbacks.reopen = Some(callback);
457 }
458
459 fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
460 self.state.borrow_mut().menus = menus.into_iter().map(|menu| menu.owned()).collect();
461 }
462
463 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
464 Some(self.state.borrow().menus.clone())
465 }
466
467 // todo(windows)
468 fn set_dock_menu(&self, _menus: Vec<MenuItem>, _keymap: &Keymap) {}
469
470 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
471 self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
472 }
473
474 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
475 self.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
476 }
477
478 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
479 self.state.borrow_mut().callbacks.validate_app_menu_command = Some(callback);
480 }
481
482 fn app_path(&self) -> Result<PathBuf> {
483 Ok(std::env::current_exe()?)
484 }
485
486 // todo(windows)
487 fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
488 Err(anyhow!("not yet implemented"))
489 }
490
491 fn set_cursor_style(&self, style: CursorStyle) {
492 let hcursor = load_cursor(style);
493 let mut lock = self.state.borrow_mut();
494 if lock.current_cursor.0 != hcursor.0 {
495 self.post_message(CURSOR_STYLE_CHANGED, WPARAM(0), LPARAM(hcursor.0 as isize));
496 lock.current_cursor = hcursor;
497 }
498 }
499
500 fn should_auto_hide_scrollbars(&self) -> bool {
501 should_auto_hide_scrollbars().log_err().unwrap_or(false)
502 }
503
504 fn write_to_clipboard(&self, item: ClipboardItem) {
505 write_to_clipboard(item);
506 }
507
508 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
509 read_from_clipboard()
510 }
511
512 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
513 let mut password = password.to_vec();
514 let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
515 let mut target_name = windows_credentials_target_name(url)
516 .encode_utf16()
517 .chain(Some(0))
518 .collect_vec();
519 self.foreground_executor().spawn(async move {
520 let credentials = CREDENTIALW {
521 LastWritten: unsafe { GetSystemTimeAsFileTime() },
522 Flags: CRED_FLAGS(0),
523 Type: CRED_TYPE_GENERIC,
524 TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
525 CredentialBlobSize: password.len() as u32,
526 CredentialBlob: password.as_ptr() as *mut _,
527 Persist: CRED_PERSIST_LOCAL_MACHINE,
528 UserName: PWSTR::from_raw(username.as_mut_ptr()),
529 ..CREDENTIALW::default()
530 };
531 unsafe { CredWriteW(&credentials, 0) }?;
532 Ok(())
533 })
534 }
535
536 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
537 let mut target_name = windows_credentials_target_name(url)
538 .encode_utf16()
539 .chain(Some(0))
540 .collect_vec();
541 self.foreground_executor().spawn(async move {
542 let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
543 unsafe {
544 CredReadW(
545 PCWSTR::from_raw(target_name.as_ptr()),
546 CRED_TYPE_GENERIC,
547 0,
548 &mut credentials,
549 )?
550 };
551
552 if credentials.is_null() {
553 Ok(None)
554 } else {
555 let username: String = unsafe { (*credentials).UserName.to_string()? };
556 let credential_blob = unsafe {
557 std::slice::from_raw_parts(
558 (*credentials).CredentialBlob,
559 (*credentials).CredentialBlobSize as usize,
560 )
561 };
562 let password = credential_blob.to_vec();
563 unsafe { CredFree(credentials as *const _ as _) };
564 Ok(Some((username, password)))
565 }
566 })
567 }
568
569 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
570 let mut target_name = windows_credentials_target_name(url)
571 .encode_utf16()
572 .chain(Some(0))
573 .collect_vec();
574 self.foreground_executor().spawn(async move {
575 unsafe { CredDeleteW(PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, 0)? };
576 Ok(())
577 })
578 }
579
580 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
581 Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
582 }
583}
584
585impl Drop for WindowsPlatform {
586 fn drop(&mut self) {
587 unsafe {
588 ManuallyDrop::drop(&mut self.bitmap_factory);
589 OleUninitialize();
590 }
591 }
592}
593
594pub(crate) struct WindowCreationInfo {
595 pub(crate) icon: HICON,
596 pub(crate) executor: ForegroundExecutor,
597 pub(crate) current_cursor: HCURSOR,
598 pub(crate) windows_version: WindowsVersion,
599 pub(crate) validation_number: usize,
600 pub(crate) main_receiver: flume::Receiver<Runnable>,
601}
602
603fn open_target(target: &str) {
604 unsafe {
605 let ret = ShellExecuteW(
606 None,
607 windows::core::w!("open"),
608 &HSTRING::from(target),
609 None,
610 None,
611 SW_SHOWDEFAULT,
612 );
613 if ret.0 as isize <= 32 {
614 log::error!("Unable to open target: {}", std::io::Error::last_os_error());
615 }
616 }
617}
618
619fn open_target_in_explorer(target: &str) {
620 unsafe {
621 let ret = ShellExecuteW(
622 None,
623 windows::core::w!("open"),
624 windows::core::w!("explorer.exe"),
625 &HSTRING::from(format!("/select,{}", target).as_str()),
626 None,
627 SW_SHOWDEFAULT,
628 );
629 if ret.0 as isize <= 32 {
630 log::error!(
631 "Unable to open target in explorer: {}",
632 std::io::Error::last_os_error()
633 );
634 }
635 }
636}
637
638fn file_open_dialog(options: PathPromptOptions) -> Result<Option<Vec<PathBuf>>> {
639 let folder_dialog: IFileOpenDialog =
640 unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? };
641
642 let mut dialog_options = FOS_FILEMUSTEXIST;
643 if options.multiple {
644 dialog_options |= FOS_ALLOWMULTISELECT;
645 }
646 if options.directories {
647 dialog_options |= FOS_PICKFOLDERS;
648 }
649
650 unsafe {
651 folder_dialog.SetOptions(dialog_options)?;
652 if folder_dialog.Show(None).is_err() {
653 // User cancelled
654 return Ok(None);
655 }
656 }
657
658 let results = unsafe { folder_dialog.GetResults()? };
659 let file_count = unsafe { results.GetCount()? };
660 if file_count == 0 {
661 return Ok(None);
662 }
663
664 let mut paths = Vec::new();
665 for i in 0..file_count {
666 let item = unsafe { results.GetItemAt(i)? };
667 let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };
668 paths.push(PathBuf::from(path));
669 }
670
671 Ok(Some(paths))
672}
673
674fn file_save_dialog(directory: PathBuf) -> Result<Option<PathBuf>> {
675 let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };
676 if !directory.to_string_lossy().is_empty() {
677 if let Some(full_path) = directory.canonicalize().log_err() {
678 let full_path = SanitizedPath::from(full_path);
679 let full_path_string = full_path.to_string();
680 let path_item: IShellItem =
681 unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_string), None)? };
682 unsafe { dialog.SetFolder(&path_item).log_err() };
683 }
684 }
685 unsafe {
686 dialog.SetFileTypes(&[Common::COMDLG_FILTERSPEC {
687 pszName: windows::core::w!("All files"),
688 pszSpec: windows::core::w!("*.*"),
689 }])?;
690 if dialog.Show(None).is_err() {
691 // User cancelled
692 return Ok(None);
693 }
694 }
695 let shell_item = unsafe { dialog.GetResult()? };
696 let file_path_string = unsafe {
697 let pwstr = shell_item.GetDisplayName(SIGDN_FILESYSPATH)?;
698 let string = pwstr.to_string()?;
699 CoTaskMemFree(Some(pwstr.0 as _));
700 string
701 };
702 Ok(Some(PathBuf::from(file_path_string)))
703}
704
705fn begin_vsync(vsync_event: HANDLE) {
706 let event: SafeHandle = vsync_event.into();
707 std::thread::spawn(move || unsafe {
708 loop {
709 windows::Win32::Graphics::Dwm::DwmFlush().log_err();
710 SetEvent(*event).log_err();
711 }
712 });
713}
714
715fn load_icon() -> Result<HICON> {
716 let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
717 let handle = unsafe {
718 LoadImageW(
719 module,
720 IDI_APPLICATION,
721 IMAGE_ICON,
722 0,
723 0,
724 LR_DEFAULTSIZE | LR_SHARED,
725 )
726 .context("unable to load icon file")?
727 };
728 Ok(HICON(handle.0))
729}
730
731#[inline]
732fn should_auto_hide_scrollbars() -> Result<bool> {
733 let ui_settings = UISettings::new()?;
734 Ok(ui_settings.AutoHideScrollBars()?)
735}
736
737#[cfg(test)]
738mod tests {
739 use crate::{ClipboardItem, Platform, WindowsPlatform};
740
741 #[test]
742 fn test_clipboard() {
743 let platform = WindowsPlatform::new();
744 let item = ClipboardItem::new_string("你好".to_string());
745 platform.write_to_clipboard(item.clone());
746 assert_eq!(platform.read_from_clipboard(), Some(item));
747
748 let item = ClipboardItem::new_string("12345".to_string());
749 platform.write_to_clipboard(item.clone());
750 assert_eq!(platform.read_from_clipboard(), Some(item));
751
752 let item = ClipboardItem::new_string_with_json_metadata("abcdef".to_string(), vec![3, 4]);
753 platform.write_to_clipboard(item.clone());
754 assert_eq!(platform.read_from_clipboard(), Some(item));
755 }
756}