platform.rs

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