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 time::UtcOffset;
 20use windows::{
 21    core::*,
 22    Win32::{
 23        Foundation::*,
 24        Globalization::u_memcpy,
 25        Graphics::Gdi::*,
 26        Security::Credentials::*,
 27        System::{
 28            Com::*,
 29            DataExchange::{
 30                CloseClipboard, EmptyClipboard, GetClipboardData, OpenClipboard,
 31                RegisterClipboardFormatW, SetClipboardData,
 32            },
 33            LibraryLoader::*,
 34            Memory::{GlobalAlloc, GlobalLock, GlobalUnlock, GMEM_MOVEABLE},
 35            Ole::*,
 36            SystemInformation::*,
 37            Threading::*,
 38            Time::*,
 39        },
 40        UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
 41    },
 42    UI::ViewManagement::UISettings,
 43};
 44
 45use crate::*;
 46
 47pub(crate) struct WindowsPlatform {
 48    state: RefCell<WindowsPlatformState>,
 49    raw_window_handles: RwLock<SmallVec<[HWND; 4]>>,
 50    // The below members will never change throughout the entire lifecycle of the app.
 51    icon: HICON,
 52    background_executor: BackgroundExecutor,
 53    foreground_executor: ForegroundExecutor,
 54    text_system: Arc<dyn PlatformTextSystem>,
 55    clipboard_hash_format: u32,
 56    clipboard_metadata_format: u32,
 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 text_system = if let Some(direct_write) = DirectWriteTextSystem::new().log_err() {
 96            log::info!("Using direct write text system.");
 97            Arc::new(direct_write) as Arc<dyn PlatformTextSystem>
 98        } else {
 99            log::info!("Using cosmic text system.");
100            Arc::new(CosmicTextSystem::new()) as Arc<dyn PlatformTextSystem>
101        };
102        let icon = load_icon().unwrap_or_default();
103        let state = RefCell::new(WindowsPlatformState::new());
104        let raw_window_handles = RwLock::new(SmallVec::new());
105        let clipboard_hash_format = register_clipboard_format(CLIPBOARD_HASH_FORMAT).unwrap();
106        let clipboard_metadata_format =
107            register_clipboard_format(CLIPBOARD_METADATA_FORMAT).unwrap();
108
109        Self {
110            state,
111            raw_window_handles,
112            icon,
113            background_executor,
114            foreground_executor,
115            text_system,
116            clipboard_hash_format,
117            clipboard_metadata_format,
118        }
119    }
120
121    fn redraw_all(&self) {
122        for handle in self.raw_window_handles.read().iter() {
123            unsafe {
124                RedrawWindow(
125                    *handle,
126                    None,
127                    HRGN::default(),
128                    RDW_INVALIDATE | RDW_UPDATENOW,
129                )
130                .ok()
131                .log_err();
132            }
133        }
134    }
135
136    pub fn try_get_windows_inner_from_hwnd(&self, hwnd: HWND) -> Option<Rc<WindowsWindowStatePtr>> {
137        self.raw_window_handles
138            .read()
139            .iter()
140            .find(|entry| *entry == &hwnd)
141            .and_then(|hwnd| try_get_window_inner(*hwnd))
142    }
143
144    #[inline]
145    fn post_message(&self, message: u32, wparam: WPARAM, lparam: LPARAM) {
146        self.raw_window_handles
147            .read()
148            .iter()
149            .for_each(|handle| unsafe {
150                PostMessageW(*handle, message, wparam, lparam).log_err();
151            });
152    }
153
154    fn close_one_window(&self, target_window: HWND) -> bool {
155        let mut lock = self.raw_window_handles.write();
156        let index = lock
157            .iter()
158            .position(|handle| *handle == target_window)
159            .unwrap();
160        lock.remove(index);
161
162        lock.is_empty()
163    }
164}
165
166impl Platform for WindowsPlatform {
167    fn background_executor(&self) -> BackgroundExecutor {
168        self.background_executor.clone()
169    }
170
171    fn foreground_executor(&self) -> ForegroundExecutor {
172        self.foreground_executor.clone()
173    }
174
175    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
176        self.text_system.clone()
177    }
178
179    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
180        on_finish_launching();
181        let vsync_event = unsafe { Owned::new(CreateEventW(None, false, false, None).unwrap()) };
182        begin_vsync(*vsync_event);
183        'a: loop {
184            let wait_result = unsafe {
185                MsgWaitForMultipleObjects(Some(&[*vsync_event]), false, INFINITE, QS_ALLINPUT)
186            };
187
188            match wait_result {
189                // compositor clock ticked so we should draw a frame
190                WAIT_EVENT(0) => {
191                    self.redraw_all();
192                }
193                // Windows thread messages are posted
194                WAIT_EVENT(1) => {
195                    let mut msg = MSG::default();
196                    unsafe {
197                        while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
198                            match msg.message {
199                                WM_QUIT => break 'a,
200                                CLOSE_ONE_WINDOW => {
201                                    if self.close_one_window(HWND(msg.lParam.0)) {
202                                        break 'a;
203                                    }
204                                }
205                                _ => {
206                                    // todo(windows)
207                                    // crate `windows 0.56` reports true as Err
208                                    TranslateMessage(&msg).as_bool();
209                                    DispatchMessageW(&msg);
210                                }
211                            }
212                        }
213                    }
214                }
215                _ => {
216                    log::error!("Something went wrong while waiting {:?}", wait_result);
217                    break;
218                }
219            }
220        }
221
222        if let Some(ref mut callback) = self.state.borrow_mut().callbacks.quit {
223            callback();
224        }
225    }
226
227    fn quit(&self) {
228        self.foreground_executor()
229            .spawn(async { unsafe { PostQuitMessage(0) } })
230            .detach();
231    }
232
233    fn restart(&self, _: Option<PathBuf>) {
234        let pid = std::process::id();
235        let Some(app_path) = self.app_path().log_err() else {
236            return;
237        };
238        let script = format!(
239            r#"
240            $pidToWaitFor = {}
241            $exePath = "{}"
242
243            while ($true) {{
244                $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
245                if (-not $process) {{
246                    Start-Process -FilePath $exePath
247                    break
248                }}
249                Start-Sleep -Seconds 0.1
250            }}
251            "#,
252            pid,
253            app_path.display(),
254        );
255        let restart_process = std::process::Command::new("powershell.exe")
256            .arg("-command")
257            .arg(script)
258            .spawn();
259
260        match restart_process {
261            Ok(_) => self.quit(),
262            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
263        }
264    }
265
266    // todo(windows)
267    fn activate(&self, ignoring_other_apps: bool) {}
268
269    // todo(windows)
270    fn hide(&self) {
271        unimplemented!()
272    }
273
274    // todo(windows)
275    fn hide_other_apps(&self) {
276        unimplemented!()
277    }
278
279    // todo(windows)
280    fn unhide_other_apps(&self) {
281        unimplemented!()
282    }
283
284    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
285        WindowsDisplay::displays()
286    }
287
288    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
289        WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
290    }
291
292    fn active_window(&self) -> Option<AnyWindowHandle> {
293        let active_window_hwnd = unsafe { GetActiveWindow() };
294        self.try_get_windows_inner_from_hwnd(active_window_hwnd)
295            .map(|inner| inner.handle)
296    }
297
298    fn open_window(
299        &self,
300        handle: AnyWindowHandle,
301        options: WindowParams,
302    ) -> Result<Box<dyn PlatformWindow>> {
303        let lock = self.state.borrow();
304        let window = WindowsWindow::new(
305            handle,
306            options,
307            self.icon,
308            self.foreground_executor.clone(),
309            lock.current_cursor,
310        )?;
311        drop(lock);
312        let handle = window.get_raw_handle();
313        self.raw_window_handles.write().push(handle);
314
315        Ok(Box::new(window))
316    }
317
318    fn window_appearance(&self) -> WindowAppearance {
319        system_appearance().log_err().unwrap_or_default()
320    }
321
322    fn open_url(&self, url: &str) {
323        let url_string = url.to_string();
324        self.background_executor()
325            .spawn(async move {
326                if url_string.is_empty() {
327                    return;
328                }
329                open_target(url_string.as_str());
330            })
331            .detach();
332    }
333
334    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
335        self.state.borrow_mut().callbacks.open_urls = Some(callback);
336    }
337
338    fn prompt_for_paths(&self, options: PathPromptOptions) -> Receiver<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(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.len() == 0 {
397                        tx.send(None).unwrap();
398                    } else {
399                        tx.send(Some(paths)).unwrap();
400                    }
401                }
402            })
403            .detach();
404
405        rx
406    }
407
408    fn prompt_for_new_path(&self, directory: &Path) -> Receiver<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(None);
416                        return;
417                    };
418                    let Ok(_) = dialog.Show(None) else {
419                        let _ = tx.send(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(Some(PathBuf::from(file.to_string().unwrap())));
425                            return;
426                        }
427                    }
428                    let _ = tx.send(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    fn local_timezone(&self) -> UtcOffset {
483        let mut info = unsafe { std::mem::zeroed() };
484        let ret = unsafe { GetTimeZoneInformation(&mut info) };
485        if ret == TIME_ZONE_ID_INVALID {
486            log::error!(
487                "Unable to get local timezone: {}",
488                std::io::Error::last_os_error()
489            );
490            return UtcOffset::UTC;
491        }
492        // Windows treat offset as:
493        // UTC = localtime + offset
494        // so we add a minus here
495        let hours = -info.Bias / 60;
496        let minutes = -info.Bias % 60;
497
498        UtcOffset::from_hms(hours as _, minutes as _, 0).unwrap()
499    }
500
501    // todo(windows)
502    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
503        Err(anyhow!("not yet implemented"))
504    }
505
506    fn set_cursor_style(&self, style: CursorStyle) {
507        let hcursor = load_cursor(style);
508        let mut lock = self.state.borrow_mut();
509        if lock.current_cursor.0 != hcursor.0 {
510            self.post_message(CURSOR_STYLE_CHANGED, WPARAM(0), LPARAM(hcursor.0));
511            lock.current_cursor = hcursor;
512        }
513    }
514
515    fn should_auto_hide_scrollbars(&self) -> bool {
516        should_auto_hide_scrollbars().log_err().unwrap_or(false)
517    }
518
519    fn write_to_clipboard(&self, item: ClipboardItem) {
520        write_to_clipboard(
521            item,
522            self.clipboard_hash_format,
523            self.clipboard_metadata_format,
524        );
525    }
526
527    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
528        read_from_clipboard(self.clipboard_hash_format, self.clipboard_metadata_format)
529    }
530
531    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
532        let mut password = password.to_vec();
533        let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
534        let mut target_name = windows_credentials_target_name(url)
535            .encode_utf16()
536            .chain(Some(0))
537            .collect_vec();
538        self.foreground_executor().spawn(async move {
539            let credentials = CREDENTIALW {
540                LastWritten: unsafe { GetSystemTimeAsFileTime() },
541                Flags: CRED_FLAGS(0),
542                Type: CRED_TYPE_GENERIC,
543                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
544                CredentialBlobSize: password.len() as u32,
545                CredentialBlob: password.as_ptr() as *mut _,
546                Persist: CRED_PERSIST_LOCAL_MACHINE,
547                UserName: PWSTR::from_raw(username.as_mut_ptr()),
548                ..CREDENTIALW::default()
549            };
550            unsafe { CredWriteW(&credentials, 0) }?;
551            Ok(())
552        })
553    }
554
555    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
556        let mut target_name = windows_credentials_target_name(url)
557            .encode_utf16()
558            .chain(Some(0))
559            .collect_vec();
560        self.foreground_executor().spawn(async move {
561            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
562            unsafe {
563                CredReadW(
564                    PCWSTR::from_raw(target_name.as_ptr()),
565                    CRED_TYPE_GENERIC,
566                    0,
567                    &mut credentials,
568                )?
569            };
570
571            if credentials.is_null() {
572                Ok(None)
573            } else {
574                let username: String = unsafe { (*credentials).UserName.to_string()? };
575                let credential_blob = unsafe {
576                    std::slice::from_raw_parts(
577                        (*credentials).CredentialBlob,
578                        (*credentials).CredentialBlobSize as usize,
579                    )
580                };
581                let password = credential_blob.to_vec();
582                unsafe { CredFree(credentials as *const c_void) };
583                Ok(Some((username, password)))
584            }
585        })
586    }
587
588    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
589        let mut target_name = windows_credentials_target_name(url)
590            .encode_utf16()
591            .chain(Some(0))
592            .collect_vec();
593        self.foreground_executor().spawn(async move {
594            unsafe { CredDeleteW(PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, 0)? };
595            Ok(())
596        })
597    }
598
599    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
600        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
601    }
602}
603
604impl Drop for WindowsPlatform {
605    fn drop(&mut self) {
606        self.text_system.destroy();
607        unsafe { OleUninitialize() };
608    }
609}
610
611fn open_target(target: &str) {
612    unsafe {
613        let ret = ShellExecuteW(
614            None,
615            windows::core::w!("open"),
616            &HSTRING::from(target),
617            None,
618            None,
619            SW_SHOWDEFAULT,
620        );
621        if ret.0 <= 32 {
622            log::error!("Unable to open target: {}", std::io::Error::last_os_error());
623        }
624    }
625}
626
627fn open_target_in_explorer(target: &str) {
628    unsafe {
629        let ret = ShellExecuteW(
630            None,
631            windows::core::w!("open"),
632            windows::core::w!("explorer.exe"),
633            &HSTRING::from(format!("/select,{}", target).as_str()),
634            None,
635            SW_SHOWDEFAULT,
636        );
637        if ret.0 <= 32 {
638            log::error!(
639                "Unable to open target in explorer: {}",
640                std::io::Error::last_os_error()
641            );
642        }
643    }
644}
645
646unsafe fn show_savefile_dialog(directory: PathBuf) -> Result<IFileSaveDialog> {
647    let dialog: IFileSaveDialog = CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)?;
648    let bind_context = CreateBindCtx(0)?;
649    let Ok(full_path) = directory.canonicalize() else {
650        return Ok(dialog);
651    };
652    let dir_str = full_path.into_os_string();
653    if dir_str.is_empty() {
654        return Ok(dialog);
655    }
656    let dir_vec = dir_str.encode_wide().collect_vec();
657    let ret = SHCreateItemFromParsingName(PCWSTR::from_raw(dir_vec.as_ptr()), &bind_context)
658        .inspect_err(|e| log::error!("unable to create IShellItem: {}", e));
659    if ret.is_ok() {
660        let dir_shell_item: IShellItem = ret.unwrap();
661        let _ = dialog
662            .SetFolder(&dir_shell_item)
663            .inspect_err(|e| log::error!("unable to set folder for save file dialog: {}", e));
664    }
665
666    Ok(dialog)
667}
668
669fn begin_vsync(vsync_evnet: HANDLE) {
670    std::thread::spawn(move || unsafe {
671        loop {
672            windows::Win32::Graphics::Dwm::DwmFlush().log_err();
673            SetEvent(vsync_evnet).log_err();
674        }
675    });
676}
677
678fn load_icon() -> Result<HICON> {
679    let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
680    let handle = unsafe {
681        LoadImageW(
682            module,
683            IDI_APPLICATION,
684            IMAGE_ICON,
685            0,
686            0,
687            LR_DEFAULTSIZE | LR_SHARED,
688        )
689        .context("unable to load icon file")?
690    };
691    Ok(HICON(handle.0))
692}
693
694#[inline]
695fn should_auto_hide_scrollbars() -> Result<bool> {
696    let ui_settings = UISettings::new()?;
697    Ok(ui_settings.AutoHideScrollBars()?)
698}
699
700fn register_clipboard_format(format: PCWSTR) -> Result<u32> {
701    let ret = unsafe { RegisterClipboardFormatW(format) };
702    if ret == 0 {
703        Err(anyhow::anyhow!(
704            "Error when registering clipboard format: {}",
705            std::io::Error::last_os_error()
706        ))
707    } else {
708        Ok(ret)
709    }
710}
711
712fn write_to_clipboard(item: ClipboardItem, hash_format: u32, metadata_format: u32) {
713    write_to_clipboard_inner(item, hash_format, metadata_format).log_err();
714    unsafe { CloseClipboard().log_err() };
715}
716
717fn write_to_clipboard_inner(
718    item: ClipboardItem,
719    hash_format: u32,
720    metadata_format: u32,
721) -> Result<()> {
722    unsafe {
723        OpenClipboard(None)?;
724        EmptyClipboard()?;
725        let encode_wide = item.text.encode_utf16().chain(Some(0)).collect_vec();
726        set_data_to_clipboard(&encode_wide, CF_UNICODETEXT.0 as u32)?;
727
728        if let Some(ref metadata) = item.metadata {
729            let hash_result = {
730                let hash = ClipboardItem::text_hash(&item.text);
731                hash.to_ne_bytes()
732            };
733            let encode_wide = std::slice::from_raw_parts(hash_result.as_ptr().cast::<u16>(), 4);
734            set_data_to_clipboard(encode_wide, hash_format)?;
735
736            let metadata_wide = metadata.encode_utf16().chain(Some(0)).collect_vec();
737            set_data_to_clipboard(&metadata_wide, metadata_format)?;
738        }
739    }
740    Ok(())
741}
742
743fn set_data_to_clipboard(data: &[u16], format: u32) -> Result<()> {
744    unsafe {
745        let global = GlobalAlloc(GMEM_MOVEABLE, data.len() * 2)?;
746        let handle = GlobalLock(global);
747        u_memcpy(handle as _, data.as_ptr(), data.len() as _);
748        let _ = GlobalUnlock(global);
749        SetClipboardData(format, HANDLE(global.0 as isize))?;
750    }
751    Ok(())
752}
753
754fn read_from_clipboard(hash_format: u32, metadata_format: u32) -> Option<ClipboardItem> {
755    let result = read_from_clipboard_inner(hash_format, metadata_format).log_err();
756    unsafe { CloseClipboard().log_err() };
757    result
758}
759
760fn read_from_clipboard_inner(hash_format: u32, metadata_format: u32) -> Result<ClipboardItem> {
761    unsafe {
762        OpenClipboard(None)?;
763        let text = {
764            let handle = GetClipboardData(CF_UNICODETEXT.0 as u32)?;
765            let text = PCWSTR(handle.0 as *const u16);
766            String::from_utf16_lossy(text.as_wide())
767        };
768        let mut item = ClipboardItem {
769            text,
770            metadata: None,
771        };
772        let Some(hash) = read_hash_from_clipboard(hash_format) else {
773            return Ok(item);
774        };
775        let Some(metadata) = read_metadata_from_clipboard(metadata_format) else {
776            return Ok(item);
777        };
778        if hash == ClipboardItem::text_hash(&item.text) {
779            item.metadata = Some(metadata);
780        }
781        Ok(item)
782    }
783}
784
785fn read_hash_from_clipboard(hash_format: u32) -> Option<u64> {
786    unsafe {
787        let handle = GetClipboardData(hash_format).log_err()?;
788        let raw_ptr = handle.0 as *const u16;
789        let hash_bytes: [u8; 8] = std::slice::from_raw_parts(raw_ptr.cast::<u8>(), 8)
790            .to_vec()
791            .try_into()
792            .log_err()?;
793        Some(u64::from_ne_bytes(hash_bytes))
794    }
795}
796
797fn read_metadata_from_clipboard(metadata_format: u32) -> Option<String> {
798    unsafe {
799        let handle = GetClipboardData(metadata_format).log_err()?;
800        let text = PCWSTR(handle.0 as *const u16);
801        Some(String::from_utf16_lossy(text.as_wide()))
802    }
803}
804
805// clipboard
806pub const CLIPBOARD_HASH_FORMAT: PCWSTR = windows::core::w!("zed-text-hash");
807pub const CLIPBOARD_METADATA_FORMAT: PCWSTR = windows::core::w!("zed-metadata");
808
809#[cfg(test)]
810mod tests {
811    use crate::{ClipboardItem, Platform, WindowsPlatform};
812
813    #[test]
814    fn test_clipboard() {
815        let platform = WindowsPlatform::new();
816        let item = ClipboardItem::new("你好".to_string());
817        platform.write_to_clipboard(item.clone());
818        assert_eq!(platform.read_from_clipboard(), Some(item));
819
820        let item = ClipboardItem::new("12345".to_string());
821        platform.write_to_clipboard(item.clone());
822        assert_eq!(platform.read_from_clipboard(), Some(item));
823
824        let item = ClipboardItem::new("abcdef".to_string()).with_metadata(vec![3, 4]);
825        platform.write_to_clipboard(item.clone());
826        assert_eq!(platform.read_from_clipboard(), Some(item));
827    }
828}