platform.rs

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