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<dyn PlatformTextSystem>,
 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 = if let Some(direct_write) = DirectWriteTextSystem::new().log_err() {
 94            log::info!("Using direct write text system.");
 95            Arc::new(direct_write) as Arc<dyn PlatformTextSystem>
 96        } else {
 97            log::info!("Using cosmic text system.");
 98            Arc::new(CosmicTextSystem::new()) as Arc<dyn PlatformTextSystem>
 99        };
100        let icon = load_icon().unwrap_or_default();
101        let state = RefCell::new(WindowsPlatformState::new());
102        let raw_window_handles = RwLock::new(SmallVec::new());
103        let clipboard_hash_format = register_clipboard_format(CLIPBOARD_HASH_FORMAT).unwrap();
104        let clipboard_metadata_format =
105            register_clipboard_format(CLIPBOARD_METADATA_FORMAT).unwrap();
106
107        Self {
108            state,
109            raw_window_handles,
110            icon,
111            background_executor,
112            foreground_executor,
113            text_system,
114            clipboard_hash_format,
115            clipboard_metadata_format,
116        }
117    }
118
119    fn redraw_all(&self) {
120        for handle in self.raw_window_handles.read().iter() {
121            unsafe {
122                RedrawWindow(
123                    *handle,
124                    None,
125                    HRGN::default(),
126                    RDW_INVALIDATE | RDW_UPDATENOW,
127                )
128                .ok()
129                .log_err();
130            }
131        }
132    }
133
134    pub fn try_get_windows_inner_from_hwnd(&self, hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
135        self.raw_window_handles
136            .read()
137            .iter()
138            .find(|entry| *entry == &hwnd)
139            .and_then(|hwnd| try_get_window_inner(*hwnd))
140    }
141
142    #[inline]
143    fn post_message(&self, message: u32, wparam: WPARAM, lparam: LPARAM) {
144        self.raw_window_handles
145            .read()
146            .iter()
147            .for_each(|handle| unsafe {
148                PostMessageW(*handle, message, wparam, lparam).log_err();
149            });
150    }
151
152    fn close_one_window(&self, target_window: HWND) -> bool {
153        let mut lock = self.raw_window_handles.write();
154        let index = lock
155            .iter()
156            .position(|handle| *handle == target_window)
157            .unwrap();
158        lock.remove(index);
159
160        lock.is_empty()
161    }
162}
163
164impl Platform for WindowsPlatform {
165    fn background_executor(&self) -> BackgroundExecutor {
166        self.background_executor.clone()
167    }
168
169    fn foreground_executor(&self) -> ForegroundExecutor {
170        self.foreground_executor.clone()
171    }
172
173    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
174        self.text_system.clone()
175    }
176
177    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
178        on_finish_launching();
179        let vsync_event = unsafe { Owned::new(CreateEventW(None, false, false, None).unwrap()) };
180        begin_vsync(*vsync_event);
181        'a: loop {
182            let wait_result = unsafe {
183                MsgWaitForMultipleObjects(Some(&[*vsync_event]), false, INFINITE, QS_ALLINPUT)
184            };
185
186            match wait_result {
187                // compositor clock ticked so we should draw a frame
188                WAIT_EVENT(0) => {
189                    self.redraw_all();
190                }
191                // Windows thread messages are posted
192                WAIT_EVENT(1) => {
193                    let mut msg = MSG::default();
194                    unsafe {
195                        while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
196                            match msg.message {
197                                WM_QUIT => break 'a,
198                                CLOSE_ONE_WINDOW => {
199                                    if self.close_one_window(HWND(msg.lParam.0)) {
200                                        break 'a;
201                                    }
202                                }
203                                _ => {
204                                    // todo(windows)
205                                    // crate `windows 0.56` reports true as Err
206                                    TranslateMessage(&msg).as_bool();
207                                    DispatchMessageW(&msg);
208                                }
209                            }
210                        }
211                    }
212                }
213                _ => {
214                    log::error!("Something went wrong while waiting {:?}", wait_result);
215                    break;
216                }
217            }
218        }
219
220        if let Some(ref mut callback) = self.state.borrow_mut().callbacks.quit {
221            callback();
222        }
223    }
224
225    fn quit(&self) {
226        self.foreground_executor()
227            .spawn(async { unsafe { PostQuitMessage(0) } })
228            .detach();
229    }
230
231    fn restart(&self, _: Option<PathBuf>) {
232        let pid = std::process::id();
233        let Some(app_path) = self.app_path().log_err() else {
234            return;
235        };
236        let script = format!(
237            r#"
238            $pidToWaitFor = {}
239            $exePath = "{}"
240
241            while ($true) {{
242                $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
243                if (-not $process) {{
244                    Start-Process -FilePath $exePath
245                    break
246                }}
247                Start-Sleep -Seconds 0.1
248            }}
249            "#,
250            pid,
251            app_path.display(),
252        );
253        let restart_process = std::process::Command::new("powershell.exe")
254            .arg("-command")
255            .arg(script)
256            .spawn();
257
258        match restart_process {
259            Ok(_) => self.quit(),
260            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
261        }
262    }
263
264    // todo(windows)
265    fn activate(&self, ignoring_other_apps: bool) {}
266
267    // todo(windows)
268    fn hide(&self) {
269        unimplemented!()
270    }
271
272    // todo(windows)
273    fn hide_other_apps(&self) {
274        unimplemented!()
275    }
276
277    // todo(windows)
278    fn unhide_other_apps(&self) {
279        unimplemented!()
280    }
281
282    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
283        WindowsDisplay::displays()
284    }
285
286    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
287        WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
288    }
289
290    fn active_window(&self) -> Option<AnyWindowHandle> {
291        let active_window_hwnd = unsafe { GetActiveWindow() };
292        self.try_get_windows_inner_from_hwnd(active_window_hwnd)
293            .map(|inner| inner.handle)
294    }
295
296    fn open_window(
297        &self,
298        handle: AnyWindowHandle,
299        options: WindowParams,
300    ) -> Result<Box<dyn PlatformWindow>> {
301        let lock = self.state.borrow();
302        let window = WindowsWindow::new(
303            handle,
304            options,
305            self.icon,
306            self.foreground_executor.clone(),
307            lock.current_cursor,
308        )?;
309        drop(lock);
310        let handle = window.get_raw_handle();
311        self.raw_window_handles.write().push(handle);
312
313        Ok(Box::new(window))
314    }
315
316    fn window_appearance(&self) -> WindowAppearance {
317        system_appearance().log_err().unwrap_or_default()
318    }
319
320    fn open_url(&self, url: &str) {
321        let url_string = url.to_string();
322        self.background_executor()
323            .spawn(async move {
324                if url_string.is_empty() {
325                    return;
326                }
327                open_target(url_string.as_str());
328            })
329            .detach();
330    }
331
332    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
333        self.state.borrow_mut().callbacks.open_urls = Some(callback);
334    }
335
336    fn prompt_for_paths(
337        &self,
338        options: PathPromptOptions,
339    ) -> Receiver<Result<Option<Vec<PathBuf>>>> {
340        let (tx, rx) = oneshot::channel();
341
342        self.foreground_executor()
343            .spawn(async move {
344                let tx = Cell::new(Some(tx));
345
346                // create file open dialog
347                let folder_dialog: IFileOpenDialog = unsafe {
348                    CoCreateInstance::<std::option::Option<&IUnknown>, IFileOpenDialog>(
349                        &FileOpenDialog,
350                        None,
351                        CLSCTX_ALL,
352                    )
353                    .unwrap()
354                };
355
356                // dialog options
357                let mut dialog_options: FILEOPENDIALOGOPTIONS = FOS_FILEMUSTEXIST;
358                if options.multiple {
359                    dialog_options |= FOS_ALLOWMULTISELECT;
360                }
361                if options.directories {
362                    dialog_options |= FOS_PICKFOLDERS;
363                }
364
365                unsafe {
366                    folder_dialog.SetOptions(dialog_options).unwrap();
367                    folder_dialog
368                        .SetTitle(&HSTRING::from(OsString::from("Select a folder")))
369                        .unwrap();
370                }
371
372                let hr = unsafe { folder_dialog.Show(None) };
373
374                if hr.is_err() {
375                    if hr.unwrap_err().code() == HRESULT(0x800704C7u32 as i32) {
376                        // user canceled error
377                        if let Some(tx) = tx.take() {
378                            tx.send(Ok(None)).unwrap();
379                        }
380                        return;
381                    }
382                }
383
384                let mut results = unsafe { folder_dialog.GetResults().unwrap() };
385
386                let mut paths: Vec<PathBuf> = Vec::new();
387                for i in 0..unsafe { results.GetCount().unwrap() } {
388                    let mut item: IShellItem = unsafe { results.GetItemAt(i).unwrap() };
389                    let mut path: PWSTR =
390                        unsafe { item.GetDisplayName(SIGDN_FILESYSPATH).unwrap() };
391                    let mut path_os_string = OsString::from_wide(unsafe { path.as_wide() });
392
393                    paths.push(PathBuf::from(path_os_string));
394                }
395
396                if let Some(tx) = tx.take() {
397                    if paths.is_empty() {
398                        tx.send(Ok(None)).unwrap();
399                    } else {
400                        tx.send(Ok(Some(paths))).unwrap();
401                    }
402                }
403            })
404            .detach();
405
406        rx
407    }
408
409    fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Result<Option<PathBuf>>> {
410        let directory = directory.to_owned();
411        let (tx, rx) = oneshot::channel();
412        self.foreground_executor()
413            .spawn(async move {
414                unsafe {
415                    let Ok(dialog) = show_savefile_dialog(directory) else {
416                        let _ = tx.send(Ok(None));
417                        return;
418                    };
419                    let Ok(_) = dialog.Show(None) else {
420                        let _ = tx.send(Ok(None)); // user cancel
421                        return;
422                    };
423                    if let Ok(shell_item) = dialog.GetResult() {
424                        if let Ok(file) = shell_item.GetDisplayName(SIGDN_FILESYSPATH) {
425                            let _ = tx.send(Ok(Some(PathBuf::from(file.to_string().unwrap()))));
426                            return;
427                        }
428                    }
429                    let _ = tx.send(Ok(None));
430                }
431            })
432            .detach();
433
434        rx
435    }
436
437    fn reveal_path(&self, path: &Path) {
438        let Ok(file_full_path) = path.canonicalize() else {
439            log::error!("unable to parse file path");
440            return;
441        };
442        self.background_executor()
443            .spawn(async move {
444                let Some(path) = file_full_path.to_str() else {
445                    return;
446                };
447                if path.is_empty() {
448                    return;
449                }
450                open_target_in_explorer(path);
451            })
452            .detach();
453    }
454
455    fn on_quit(&self, callback: Box<dyn FnMut()>) {
456        self.state.borrow_mut().callbacks.quit = Some(callback);
457    }
458
459    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
460        self.state.borrow_mut().callbacks.reopen = Some(callback);
461    }
462
463    // todo(windows)
464    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
465    fn set_dock_menu(&self, menus: Vec<MenuItem>, keymap: &Keymap) {}
466
467    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
468        self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
469    }
470
471    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
472        self.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
473    }
474
475    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
476        self.state.borrow_mut().callbacks.validate_app_menu_command = Some(callback);
477    }
478
479    fn app_path(&self) -> Result<PathBuf> {
480        Ok(std::env::current_exe()?)
481    }
482
483    // todo(windows)
484    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
485        Err(anyhow!("not yet implemented"))
486    }
487
488    fn set_cursor_style(&self, style: CursorStyle) {
489        let hcursor = load_cursor(style);
490        let mut lock = self.state.borrow_mut();
491        if lock.current_cursor.0 != hcursor.0 {
492            self.post_message(CURSOR_STYLE_CHANGED, WPARAM(0), LPARAM(hcursor.0));
493            lock.current_cursor = hcursor;
494        }
495    }
496
497    fn should_auto_hide_scrollbars(&self) -> bool {
498        should_auto_hide_scrollbars().log_err().unwrap_or(false)
499    }
500
501    fn write_to_clipboard(&self, item: ClipboardItem) {
502        write_to_clipboard(
503            item,
504            self.clipboard_hash_format,
505            self.clipboard_metadata_format,
506        );
507    }
508
509    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
510        read_from_clipboard(self.clipboard_hash_format, self.clipboard_metadata_format)
511    }
512
513    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
514        let mut password = password.to_vec();
515        let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
516        let mut target_name = windows_credentials_target_name(url)
517            .encode_utf16()
518            .chain(Some(0))
519            .collect_vec();
520        self.foreground_executor().spawn(async move {
521            let credentials = CREDENTIALW {
522                LastWritten: unsafe { GetSystemTimeAsFileTime() },
523                Flags: CRED_FLAGS(0),
524                Type: CRED_TYPE_GENERIC,
525                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
526                CredentialBlobSize: password.len() as u32,
527                CredentialBlob: password.as_ptr() as *mut _,
528                Persist: CRED_PERSIST_LOCAL_MACHINE,
529                UserName: PWSTR::from_raw(username.as_mut_ptr()),
530                ..CREDENTIALW::default()
531            };
532            unsafe { CredWriteW(&credentials, 0) }?;
533            Ok(())
534        })
535    }
536
537    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
538        let mut target_name = windows_credentials_target_name(url)
539            .encode_utf16()
540            .chain(Some(0))
541            .collect_vec();
542        self.foreground_executor().spawn(async move {
543            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
544            unsafe {
545                CredReadW(
546                    PCWSTR::from_raw(target_name.as_ptr()),
547                    CRED_TYPE_GENERIC,
548                    0,
549                    &mut credentials,
550                )?
551            };
552
553            if credentials.is_null() {
554                Ok(None)
555            } else {
556                let username: String = unsafe { (*credentials).UserName.to_string()? };
557                let credential_blob = unsafe {
558                    std::slice::from_raw_parts(
559                        (*credentials).CredentialBlob,
560                        (*credentials).CredentialBlobSize as usize,
561                    )
562                };
563                let password = credential_blob.to_vec();
564                unsafe { CredFree(credentials as *const c_void) };
565                Ok(Some((username, password)))
566            }
567        })
568    }
569
570    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
571        let mut target_name = windows_credentials_target_name(url)
572            .encode_utf16()
573            .chain(Some(0))
574            .collect_vec();
575        self.foreground_executor().spawn(async move {
576            unsafe { CredDeleteW(PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, 0)? };
577            Ok(())
578        })
579    }
580
581    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
582        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
583    }
584}
585
586impl Drop for WindowsPlatform {
587    fn drop(&mut self) {
588        self.text_system.destroy();
589        unsafe { OleUninitialize() };
590    }
591}
592
593fn open_target(target: &str) {
594    unsafe {
595        let ret = ShellExecuteW(
596            None,
597            windows::core::w!("open"),
598            &HSTRING::from(target),
599            None,
600            None,
601            SW_SHOWDEFAULT,
602        );
603        if ret.0 <= 32 {
604            log::error!("Unable to open target: {}", std::io::Error::last_os_error());
605        }
606    }
607}
608
609fn open_target_in_explorer(target: &str) {
610    unsafe {
611        let ret = ShellExecuteW(
612            None,
613            windows::core::w!("open"),
614            windows::core::w!("explorer.exe"),
615            &HSTRING::from(format!("/select,{}", target).as_str()),
616            None,
617            SW_SHOWDEFAULT,
618        );
619        if ret.0 <= 32 {
620            log::error!(
621                "Unable to open target in explorer: {}",
622                std::io::Error::last_os_error()
623            );
624        }
625    }
626}
627
628unsafe fn show_savefile_dialog(directory: PathBuf) -> Result<IFileSaveDialog> {
629    let dialog: IFileSaveDialog = CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)?;
630    let bind_context = CreateBindCtx(0)?;
631    let Ok(full_path) = directory.canonicalize() else {
632        return Ok(dialog);
633    };
634    let dir_str = full_path.into_os_string();
635    if dir_str.is_empty() {
636        return Ok(dialog);
637    }
638    let dir_vec = dir_str.encode_wide().collect_vec();
639    let ret = SHCreateItemFromParsingName(PCWSTR::from_raw(dir_vec.as_ptr()), &bind_context)
640        .inspect_err(|e| log::error!("unable to create IShellItem: {}", e));
641    if ret.is_ok() {
642        let dir_shell_item: IShellItem = ret.unwrap();
643        let _ = dialog
644            .SetFolder(&dir_shell_item)
645            .inspect_err(|e| log::error!("unable to set folder for save file dialog: {}", e));
646    }
647
648    Ok(dialog)
649}
650
651fn begin_vsync(vsync_evnet: HANDLE) {
652    std::thread::spawn(move || unsafe {
653        loop {
654            windows::Win32::Graphics::Dwm::DwmFlush().log_err();
655            SetEvent(vsync_evnet).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 as isize))?;
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}