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