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 open_with_system(&self, path: &Path) {
404        let Ok(full_path) = path.canonicalize() else {
405            log::error!("unable to parse file full path: {}", path.display());
406            return;
407        };
408        self.background_executor()
409            .spawn(async move {
410                let Some(full_path_str) = full_path.to_str() else {
411                    return;
412                };
413                if full_path_str.is_empty() {
414                    return;
415                };
416                open_target(full_path_str);
417            })
418            .detach();
419    }
420
421    fn on_quit(&self, callback: Box<dyn FnMut()>) {
422        self.state.borrow_mut().callbacks.quit = Some(callback);
423    }
424
425    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
426        self.state.borrow_mut().callbacks.reopen = Some(callback);
427    }
428
429    // todo(windows)
430    fn set_menus(&self, _menus: Vec<Menu>, _keymap: &Keymap) {}
431    fn set_dock_menu(&self, _menus: Vec<MenuItem>, _keymap: &Keymap) {}
432
433    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
434        self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
435    }
436
437    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
438        self.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
439    }
440
441    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
442        self.state.borrow_mut().callbacks.validate_app_menu_command = Some(callback);
443    }
444
445    fn app_path(&self) -> Result<PathBuf> {
446        Ok(std::env::current_exe()?)
447    }
448
449    // todo(windows)
450    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
451        Err(anyhow!("not yet implemented"))
452    }
453
454    fn set_cursor_style(&self, style: CursorStyle) {
455        let hcursor = load_cursor(style);
456        let mut lock = self.state.borrow_mut();
457        if lock.current_cursor.0 != hcursor.0 {
458            self.post_message(CURSOR_STYLE_CHANGED, WPARAM(0), LPARAM(hcursor.0 as isize));
459            lock.current_cursor = hcursor;
460        }
461    }
462
463    fn should_auto_hide_scrollbars(&self) -> bool {
464        should_auto_hide_scrollbars().log_err().unwrap_or(false)
465    }
466
467    fn write_to_clipboard(&self, item: ClipboardItem) {
468        write_to_clipboard(
469            item,
470            self.clipboard_hash_format,
471            self.clipboard_metadata_format,
472        );
473    }
474
475    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
476        read_from_clipboard(self.clipboard_hash_format, self.clipboard_metadata_format)
477    }
478
479    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
480        let mut password = password.to_vec();
481        let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
482        let mut target_name = windows_credentials_target_name(url)
483            .encode_utf16()
484            .chain(Some(0))
485            .collect_vec();
486        self.foreground_executor().spawn(async move {
487            let credentials = CREDENTIALW {
488                LastWritten: unsafe { GetSystemTimeAsFileTime() },
489                Flags: CRED_FLAGS(0),
490                Type: CRED_TYPE_GENERIC,
491                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
492                CredentialBlobSize: password.len() as u32,
493                CredentialBlob: password.as_ptr() as *mut _,
494                Persist: CRED_PERSIST_LOCAL_MACHINE,
495                UserName: PWSTR::from_raw(username.as_mut_ptr()),
496                ..CREDENTIALW::default()
497            };
498            unsafe { CredWriteW(&credentials, 0) }?;
499            Ok(())
500        })
501    }
502
503    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
504        let mut target_name = windows_credentials_target_name(url)
505            .encode_utf16()
506            .chain(Some(0))
507            .collect_vec();
508        self.foreground_executor().spawn(async move {
509            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
510            unsafe {
511                CredReadW(
512                    PCWSTR::from_raw(target_name.as_ptr()),
513                    CRED_TYPE_GENERIC,
514                    0,
515                    &mut credentials,
516                )?
517            };
518
519            if credentials.is_null() {
520                Ok(None)
521            } else {
522                let username: String = unsafe { (*credentials).UserName.to_string()? };
523                let credential_blob = unsafe {
524                    std::slice::from_raw_parts(
525                        (*credentials).CredentialBlob,
526                        (*credentials).CredentialBlobSize as usize,
527                    )
528                };
529                let password = credential_blob.to_vec();
530                unsafe { CredFree(credentials as *const _ as _) };
531                Ok(Some((username, password)))
532            }
533        })
534    }
535
536    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
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            unsafe { CredDeleteW(PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, 0)? };
543            Ok(())
544        })
545    }
546
547    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
548        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
549    }
550}
551
552impl Drop for WindowsPlatform {
553    fn drop(&mut self) {
554        unsafe {
555            ManuallyDrop::drop(&mut self.bitmap_factory);
556            OleUninitialize();
557        }
558    }
559}
560
561fn open_target(target: &str) {
562    unsafe {
563        let ret = ShellExecuteW(
564            None,
565            windows::core::w!("open"),
566            &HSTRING::from(target),
567            None,
568            None,
569            SW_SHOWDEFAULT,
570        );
571        if ret.0 as isize <= 32 {
572            log::error!("Unable to open target: {}", std::io::Error::last_os_error());
573        }
574    }
575}
576
577fn open_target_in_explorer(target: &str) {
578    unsafe {
579        let ret = ShellExecuteW(
580            None,
581            windows::core::w!("open"),
582            windows::core::w!("explorer.exe"),
583            &HSTRING::from(format!("/select,{}", target).as_str()),
584            None,
585            SW_SHOWDEFAULT,
586        );
587        if ret.0 as isize <= 32 {
588            log::error!(
589                "Unable to open target in explorer: {}",
590                std::io::Error::last_os_error()
591            );
592        }
593    }
594}
595
596fn file_open_dialog(options: PathPromptOptions) -> Result<Option<Vec<PathBuf>>> {
597    let folder_dialog: IFileOpenDialog =
598        unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? };
599
600    let mut dialog_options = FOS_FILEMUSTEXIST;
601    if options.multiple {
602        dialog_options |= FOS_ALLOWMULTISELECT;
603    }
604    if options.directories {
605        dialog_options |= FOS_PICKFOLDERS;
606    }
607
608    unsafe {
609        folder_dialog.SetOptions(dialog_options)?;
610        if folder_dialog.Show(None).is_err() {
611            // User cancelled
612            return Ok(None);
613        }
614    }
615
616    let results = unsafe { folder_dialog.GetResults()? };
617    let file_count = unsafe { results.GetCount()? };
618    if file_count == 0 {
619        return Ok(None);
620    }
621
622    let mut paths = Vec::new();
623    for i in 0..file_count {
624        let item = unsafe { results.GetItemAt(i)? };
625        let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };
626        paths.push(PathBuf::from(path));
627    }
628
629    Ok(Some(paths))
630}
631
632fn file_save_dialog(directory: PathBuf) -> Result<Option<PathBuf>> {
633    let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };
634    if let Some(full_path) = directory.canonicalize().log_err() {
635        let full_path = full_path.to_string_lossy().to_string();
636        if !full_path.is_empty() {
637            let path_item: IShellItem =
638                unsafe { SHCreateItemFromParsingName(&HSTRING::from(&full_path), None)? };
639            unsafe { dialog.SetFolder(&path_item).log_err() };
640        }
641    }
642    unsafe {
643        if dialog.Show(None).is_err() {
644            // User cancelled
645            return Ok(None);
646        }
647    }
648    let shell_item = unsafe { dialog.GetResult()? };
649    let file_path_string = unsafe { shell_item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };
650    Ok(Some(PathBuf::from(file_path_string)))
651}
652
653fn begin_vsync(vsync_event: HANDLE) {
654    let event: SafeHandle = vsync_event.into();
655    std::thread::spawn(move || unsafe {
656        loop {
657            windows::Win32::Graphics::Dwm::DwmFlush().log_err();
658            SetEvent(*event).log_err();
659        }
660    });
661}
662
663fn load_icon() -> Result<HICON> {
664    let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
665    let handle = unsafe {
666        LoadImageW(
667            module,
668            IDI_APPLICATION,
669            IMAGE_ICON,
670            0,
671            0,
672            LR_DEFAULTSIZE | LR_SHARED,
673        )
674        .context("unable to load icon file")?
675    };
676    Ok(HICON(handle.0))
677}
678
679#[inline]
680fn should_auto_hide_scrollbars() -> Result<bool> {
681    let ui_settings = UISettings::new()?;
682    Ok(ui_settings.AutoHideScrollBars()?)
683}
684
685fn register_clipboard_format(format: PCWSTR) -> Result<u32> {
686    let ret = unsafe { RegisterClipboardFormatW(format) };
687    if ret == 0 {
688        Err(anyhow::anyhow!(
689            "Error when registering clipboard format: {}",
690            std::io::Error::last_os_error()
691        ))
692    } else {
693        Ok(ret)
694    }
695}
696
697fn write_to_clipboard(item: ClipboardItem, hash_format: u32, metadata_format: u32) {
698    write_to_clipboard_inner(item, hash_format, metadata_format).log_err();
699    unsafe { CloseClipboard().log_err() };
700}
701
702fn write_to_clipboard_inner(
703    item: ClipboardItem,
704    hash_format: u32,
705    metadata_format: u32,
706) -> Result<()> {
707    unsafe {
708        OpenClipboard(None)?;
709        EmptyClipboard()?;
710        let encode_wide = item
711            .text()
712            .unwrap_or_default()
713            .encode_utf16()
714            .chain(Some(0))
715            .collect_vec();
716        set_data_to_clipboard(&encode_wide, CF_UNICODETEXT.0 as u32)?;
717
718        if let Some((metadata, text)) = item.metadata().zip(item.text()) {
719            let hash_result = {
720                let hash = ClipboardString::text_hash(&text);
721                hash.to_ne_bytes()
722            };
723            let encode_wide = std::slice::from_raw_parts(hash_result.as_ptr().cast::<u16>(), 4);
724            set_data_to_clipboard(encode_wide, hash_format)?;
725
726            let metadata_wide = metadata.encode_utf16().chain(Some(0)).collect_vec();
727            set_data_to_clipboard(&metadata_wide, metadata_format)?;
728        }
729    }
730    Ok(())
731}
732
733fn set_data_to_clipboard(data: &[u16], format: u32) -> Result<()> {
734    unsafe {
735        let global = GlobalAlloc(GMEM_MOVEABLE, data.len() * 2)?;
736        let handle = GlobalLock(global);
737        u_memcpy(handle as _, data.as_ptr(), data.len() as _);
738        let _ = GlobalUnlock(global);
739        SetClipboardData(format, HANDLE(global.0))?;
740    }
741    Ok(())
742}
743
744fn read_from_clipboard(hash_format: u32, metadata_format: u32) -> Option<ClipboardItem> {
745    let result = read_from_clipboard_inner(hash_format, metadata_format).log_err();
746    unsafe { CloseClipboard().log_err() };
747    result
748}
749
750fn read_from_clipboard_inner(hash_format: u32, metadata_format: u32) -> Result<ClipboardItem> {
751    unsafe {
752        OpenClipboard(None)?;
753        let text = {
754            let handle = GetClipboardData(CF_UNICODETEXT.0 as u32)?;
755            let text = PCWSTR(handle.0 as *const u16);
756            String::from_utf16_lossy(text.as_wide())
757        };
758        let Some(hash) = read_hash_from_clipboard(hash_format) else {
759            return Ok(ClipboardItem::new_string(text));
760        };
761        let Some(metadata) = read_metadata_from_clipboard(metadata_format) else {
762            return Ok(ClipboardItem::new_string(text));
763        };
764        if hash == ClipboardString::text_hash(&text) {
765            Ok(ClipboardItem::new_string_with_metadata(text, metadata))
766        } else {
767            Ok(ClipboardItem::new_string(text))
768        }
769    }
770}
771
772fn read_hash_from_clipboard(hash_format: u32) -> Option<u64> {
773    unsafe {
774        let handle = GetClipboardData(hash_format).log_err()?;
775        let raw_ptr = handle.0 as *const u16;
776        let hash_bytes: [u8; 8] = std::slice::from_raw_parts(raw_ptr.cast::<u8>(), 8)
777            .to_vec()
778            .try_into()
779            .log_err()?;
780        Some(u64::from_ne_bytes(hash_bytes))
781    }
782}
783
784fn read_metadata_from_clipboard(metadata_format: u32) -> Option<String> {
785    unsafe {
786        let handle = GetClipboardData(metadata_format).log_err()?;
787        let text = PCWSTR(handle.0 as *const u16);
788        Some(String::from_utf16_lossy(text.as_wide()))
789    }
790}
791
792// clipboard
793pub const CLIPBOARD_HASH_FORMAT: PCWSTR = windows::core::w!("zed-text-hash");
794pub const CLIPBOARD_METADATA_FORMAT: PCWSTR = windows::core::w!("zed-metadata");
795
796#[cfg(test)]
797mod tests {
798    use crate::{ClipboardItem, Platform, WindowsPlatform};
799
800    #[test]
801    fn test_clipboard() {
802        let platform = WindowsPlatform::new();
803        let item = ClipboardItem::new_string("你好".to_string());
804        platform.write_to_clipboard(item.clone());
805        assert_eq!(platform.read_from_clipboard(), Some(item));
806
807        let item = ClipboardItem::new_string("12345".to_string());
808        platform.write_to_clipboard(item.clone());
809        assert_eq!(platform.read_from_clipboard(), Some(item));
810
811        let item = ClipboardItem::new_string_with_json_metadata("abcdef".to_string(), vec![3, 4]);
812        platform.write_to_clipboard(item.clone());
813        assert_eq!(platform.read_from_clipboard(), Some(item));
814    }
815}