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