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(
339        &self,
340        options: PathPromptOptions,
341    ) -> Receiver<Result<Option<Vec<PathBuf>>>> {
342        let (tx, rx) = oneshot::channel();
343
344        self.foreground_executor()
345            .spawn(async move {
346                let tx = Cell::new(Some(tx));
347
348                // create file open dialog
349                let folder_dialog: IFileOpenDialog = unsafe {
350                    CoCreateInstance::<std::option::Option<&IUnknown>, IFileOpenDialog>(
351                        &FileOpenDialog,
352                        None,
353                        CLSCTX_ALL,
354                    )
355                    .unwrap()
356                };
357
358                // dialog options
359                let mut dialog_options: FILEOPENDIALOGOPTIONS = FOS_FILEMUSTEXIST;
360                if options.multiple {
361                    dialog_options |= FOS_ALLOWMULTISELECT;
362                }
363                if options.directories {
364                    dialog_options |= FOS_PICKFOLDERS;
365                }
366
367                unsafe {
368                    folder_dialog.SetOptions(dialog_options).unwrap();
369                    folder_dialog
370                        .SetTitle(&HSTRING::from(OsString::from("Select a folder")))
371                        .unwrap();
372                }
373
374                let hr = unsafe { folder_dialog.Show(None) };
375
376                if hr.is_err() {
377                    if hr.unwrap_err().code() == HRESULT(0x800704C7u32 as i32) {
378                        // user canceled error
379                        if let Some(tx) = tx.take() {
380                            tx.send(Ok(None)).unwrap();
381                        }
382                        return;
383                    }
384                }
385
386                let mut results = unsafe { folder_dialog.GetResults().unwrap() };
387
388                let mut paths: Vec<PathBuf> = Vec::new();
389                for i in 0..unsafe { results.GetCount().unwrap() } {
390                    let mut item: IShellItem = unsafe { results.GetItemAt(i).unwrap() };
391                    let mut path: PWSTR =
392                        unsafe { item.GetDisplayName(SIGDN_FILESYSPATH).unwrap() };
393                    let mut path_os_string = OsString::from_wide(unsafe { path.as_wide() });
394
395                    paths.push(PathBuf::from(path_os_string));
396                }
397
398                if let Some(tx) = tx.take() {
399                    if paths.is_empty() {
400                        tx.send(Ok(None)).unwrap();
401                    } else {
402                        tx.send(Ok(Some(paths))).unwrap();
403                    }
404                }
405            })
406            .detach();
407
408        rx
409    }
410
411    fn prompt_for_new_path(&self, directory: &Path) -> Receiver<Result<Option<PathBuf>>> {
412        let directory = directory.to_owned();
413        let (tx, rx) = oneshot::channel();
414        self.foreground_executor()
415            .spawn(async move {
416                unsafe {
417                    let Ok(dialog) = show_savefile_dialog(directory) else {
418                        let _ = tx.send(Ok(None));
419                        return;
420                    };
421                    let Ok(_) = dialog.Show(None) else {
422                        let _ = tx.send(Ok(None)); // user cancel
423                        return;
424                    };
425                    if let Ok(shell_item) = dialog.GetResult() {
426                        if let Ok(file) = shell_item.GetDisplayName(SIGDN_FILESYSPATH) {
427                            let _ = tx.send(Ok(Some(PathBuf::from(file.to_string().unwrap()))));
428                            return;
429                        }
430                    }
431                    let _ = tx.send(Ok(None));
432                }
433            })
434            .detach();
435
436        rx
437    }
438
439    fn reveal_path(&self, path: &Path) {
440        let Ok(file_full_path) = path.canonicalize() else {
441            log::error!("unable to parse file path");
442            return;
443        };
444        self.background_executor()
445            .spawn(async move {
446                let Some(path) = file_full_path.to_str() else {
447                    return;
448                };
449                if path.is_empty() {
450                    return;
451                }
452                open_target_in_explorer(path);
453            })
454            .detach();
455    }
456
457    fn on_quit(&self, callback: Box<dyn FnMut()>) {
458        self.state.borrow_mut().callbacks.quit = Some(callback);
459    }
460
461    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
462        self.state.borrow_mut().callbacks.reopen = Some(callback);
463    }
464
465    // todo(windows)
466    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
467    fn set_dock_menu(&self, menus: Vec<MenuItem>, keymap: &Keymap) {}
468
469    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
470        self.state.borrow_mut().callbacks.app_menu_action = Some(callback);
471    }
472
473    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
474        self.state.borrow_mut().callbacks.will_open_app_menu = Some(callback);
475    }
476
477    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
478        self.state.borrow_mut().callbacks.validate_app_menu_command = Some(callback);
479    }
480
481    fn app_path(&self) -> Result<PathBuf> {
482        Ok(std::env::current_exe()?)
483    }
484
485    fn local_timezone(&self) -> UtcOffset {
486        let mut info = unsafe { std::mem::zeroed() };
487        let ret = unsafe { GetTimeZoneInformation(&mut info) };
488        if ret == TIME_ZONE_ID_INVALID {
489            log::error!(
490                "Unable to get local timezone: {}",
491                std::io::Error::last_os_error()
492            );
493            return UtcOffset::UTC;
494        }
495        // Windows treat offset as:
496        // UTC = localtime + offset
497        // so we add a minus here
498        let hours = -info.Bias / 60;
499        let minutes = -info.Bias % 60;
500
501        UtcOffset::from_hms(hours as _, minutes as _, 0).unwrap()
502    }
503
504    // todo(windows)
505    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
506        Err(anyhow!("not yet implemented"))
507    }
508
509    fn set_cursor_style(&self, style: CursorStyle) {
510        let hcursor = load_cursor(style);
511        let mut lock = self.state.borrow_mut();
512        if lock.current_cursor.0 != hcursor.0 {
513            self.post_message(CURSOR_STYLE_CHANGED, WPARAM(0), LPARAM(hcursor.0));
514            lock.current_cursor = hcursor;
515        }
516    }
517
518    fn should_auto_hide_scrollbars(&self) -> bool {
519        should_auto_hide_scrollbars().log_err().unwrap_or(false)
520    }
521
522    fn write_to_clipboard(&self, item: ClipboardItem) {
523        write_to_clipboard(
524            item,
525            self.clipboard_hash_format,
526            self.clipboard_metadata_format,
527        );
528    }
529
530    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
531        read_from_clipboard(self.clipboard_hash_format, self.clipboard_metadata_format)
532    }
533
534    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
535        let mut password = password.to_vec();
536        let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
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 credentials = CREDENTIALW {
543                LastWritten: unsafe { GetSystemTimeAsFileTime() },
544                Flags: CRED_FLAGS(0),
545                Type: CRED_TYPE_GENERIC,
546                TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
547                CredentialBlobSize: password.len() as u32,
548                CredentialBlob: password.as_ptr() as *mut _,
549                Persist: CRED_PERSIST_LOCAL_MACHINE,
550                UserName: PWSTR::from_raw(username.as_mut_ptr()),
551                ..CREDENTIALW::default()
552            };
553            unsafe { CredWriteW(&credentials, 0) }?;
554            Ok(())
555        })
556    }
557
558    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
559        let mut target_name = windows_credentials_target_name(url)
560            .encode_utf16()
561            .chain(Some(0))
562            .collect_vec();
563        self.foreground_executor().spawn(async move {
564            let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
565            unsafe {
566                CredReadW(
567                    PCWSTR::from_raw(target_name.as_ptr()),
568                    CRED_TYPE_GENERIC,
569                    0,
570                    &mut credentials,
571                )?
572            };
573
574            if credentials.is_null() {
575                Ok(None)
576            } else {
577                let username: String = unsafe { (*credentials).UserName.to_string()? };
578                let credential_blob = unsafe {
579                    std::slice::from_raw_parts(
580                        (*credentials).CredentialBlob,
581                        (*credentials).CredentialBlobSize as usize,
582                    )
583                };
584                let password = credential_blob.to_vec();
585                unsafe { CredFree(credentials as *const c_void) };
586                Ok(Some((username, password)))
587            }
588        })
589    }
590
591    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
592        let mut target_name = windows_credentials_target_name(url)
593            .encode_utf16()
594            .chain(Some(0))
595            .collect_vec();
596        self.foreground_executor().spawn(async move {
597            unsafe { CredDeleteW(PCWSTR::from_raw(target_name.as_ptr()), CRED_TYPE_GENERIC, 0)? };
598            Ok(())
599        })
600    }
601
602    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
603        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
604    }
605}
606
607impl Drop for WindowsPlatform {
608    fn drop(&mut self) {
609        self.text_system.destroy();
610        unsafe { OleUninitialize() };
611    }
612}
613
614fn open_target(target: &str) {
615    unsafe {
616        let ret = ShellExecuteW(
617            None,
618            windows::core::w!("open"),
619            &HSTRING::from(target),
620            None,
621            None,
622            SW_SHOWDEFAULT,
623        );
624        if ret.0 <= 32 {
625            log::error!("Unable to open target: {}", std::io::Error::last_os_error());
626        }
627    }
628}
629
630fn open_target_in_explorer(target: &str) {
631    unsafe {
632        let ret = ShellExecuteW(
633            None,
634            windows::core::w!("open"),
635            windows::core::w!("explorer.exe"),
636            &HSTRING::from(format!("/select,{}", target).as_str()),
637            None,
638            SW_SHOWDEFAULT,
639        );
640        if ret.0 <= 32 {
641            log::error!(
642                "Unable to open target in explorer: {}",
643                std::io::Error::last_os_error()
644            );
645        }
646    }
647}
648
649unsafe fn show_savefile_dialog(directory: PathBuf) -> Result<IFileSaveDialog> {
650    let dialog: IFileSaveDialog = CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)?;
651    let bind_context = CreateBindCtx(0)?;
652    let Ok(full_path) = directory.canonicalize() else {
653        return Ok(dialog);
654    };
655    let dir_str = full_path.into_os_string();
656    if dir_str.is_empty() {
657        return Ok(dialog);
658    }
659    let dir_vec = dir_str.encode_wide().collect_vec();
660    let ret = SHCreateItemFromParsingName(PCWSTR::from_raw(dir_vec.as_ptr()), &bind_context)
661        .inspect_err(|e| log::error!("unable to create IShellItem: {}", e));
662    if ret.is_ok() {
663        let dir_shell_item: IShellItem = ret.unwrap();
664        let _ = dialog
665            .SetFolder(&dir_shell_item)
666            .inspect_err(|e| log::error!("unable to set folder for save file dialog: {}", e));
667    }
668
669    Ok(dialog)
670}
671
672fn begin_vsync(vsync_evnet: HANDLE) {
673    std::thread::spawn(move || unsafe {
674        loop {
675            windows::Win32::Graphics::Dwm::DwmFlush().log_err();
676            SetEvent(vsync_evnet).log_err();
677        }
678    });
679}
680
681fn load_icon() -> Result<HICON> {
682    let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
683    let handle = unsafe {
684        LoadImageW(
685            module,
686            IDI_APPLICATION,
687            IMAGE_ICON,
688            0,
689            0,
690            LR_DEFAULTSIZE | LR_SHARED,
691        )
692        .context("unable to load icon file")?
693    };
694    Ok(HICON(handle.0))
695}
696
697#[inline]
698fn should_auto_hide_scrollbars() -> Result<bool> {
699    let ui_settings = UISettings::new()?;
700    Ok(ui_settings.AutoHideScrollBars()?)
701}
702
703fn register_clipboard_format(format: PCWSTR) -> Result<u32> {
704    let ret = unsafe { RegisterClipboardFormatW(format) };
705    if ret == 0 {
706        Err(anyhow::anyhow!(
707            "Error when registering clipboard format: {}",
708            std::io::Error::last_os_error()
709        ))
710    } else {
711        Ok(ret)
712    }
713}
714
715fn write_to_clipboard(item: ClipboardItem, hash_format: u32, metadata_format: u32) {
716    write_to_clipboard_inner(item, hash_format, metadata_format).log_err();
717    unsafe { CloseClipboard().log_err() };
718}
719
720fn write_to_clipboard_inner(
721    item: ClipboardItem,
722    hash_format: u32,
723    metadata_format: u32,
724) -> Result<()> {
725    unsafe {
726        OpenClipboard(None)?;
727        EmptyClipboard()?;
728        let encode_wide = item.text.encode_utf16().chain(Some(0)).collect_vec();
729        set_data_to_clipboard(&encode_wide, CF_UNICODETEXT.0 as u32)?;
730
731        if let Some(ref metadata) = item.metadata {
732            let hash_result = {
733                let hash = ClipboardItem::text_hash(&item.text);
734                hash.to_ne_bytes()
735            };
736            let encode_wide = std::slice::from_raw_parts(hash_result.as_ptr().cast::<u16>(), 4);
737            set_data_to_clipboard(encode_wide, hash_format)?;
738
739            let metadata_wide = metadata.encode_utf16().chain(Some(0)).collect_vec();
740            set_data_to_clipboard(&metadata_wide, metadata_format)?;
741        }
742    }
743    Ok(())
744}
745
746fn set_data_to_clipboard(data: &[u16], format: u32) -> Result<()> {
747    unsafe {
748        let global = GlobalAlloc(GMEM_MOVEABLE, data.len() * 2)?;
749        let handle = GlobalLock(global);
750        u_memcpy(handle as _, data.as_ptr(), data.len() as _);
751        let _ = GlobalUnlock(global);
752        SetClipboardData(format, HANDLE(global.0 as isize))?;
753    }
754    Ok(())
755}
756
757fn read_from_clipboard(hash_format: u32, metadata_format: u32) -> Option<ClipboardItem> {
758    let result = read_from_clipboard_inner(hash_format, metadata_format).log_err();
759    unsafe { CloseClipboard().log_err() };
760    result
761}
762
763fn read_from_clipboard_inner(hash_format: u32, metadata_format: u32) -> Result<ClipboardItem> {
764    unsafe {
765        OpenClipboard(None)?;
766        let text = {
767            let handle = GetClipboardData(CF_UNICODETEXT.0 as u32)?;
768            let text = PCWSTR(handle.0 as *const u16);
769            String::from_utf16_lossy(text.as_wide())
770        };
771        let mut item = ClipboardItem {
772            text,
773            metadata: None,
774        };
775        let Some(hash) = read_hash_from_clipboard(hash_format) else {
776            return Ok(item);
777        };
778        let Some(metadata) = read_metadata_from_clipboard(metadata_format) else {
779            return Ok(item);
780        };
781        if hash == ClipboardItem::text_hash(&item.text) {
782            item.metadata = Some(metadata);
783        }
784        Ok(item)
785    }
786}
787
788fn read_hash_from_clipboard(hash_format: u32) -> Option<u64> {
789    unsafe {
790        let handle = GetClipboardData(hash_format).log_err()?;
791        let raw_ptr = handle.0 as *const u16;
792        let hash_bytes: [u8; 8] = std::slice::from_raw_parts(raw_ptr.cast::<u8>(), 8)
793            .to_vec()
794            .try_into()
795            .log_err()?;
796        Some(u64::from_ne_bytes(hash_bytes))
797    }
798}
799
800fn read_metadata_from_clipboard(metadata_format: u32) -> Option<String> {
801    unsafe {
802        let handle = GetClipboardData(metadata_format).log_err()?;
803        let text = PCWSTR(handle.0 as *const u16);
804        Some(String::from_utf16_lossy(text.as_wide()))
805    }
806}
807
808// clipboard
809pub const CLIPBOARD_HASH_FORMAT: PCWSTR = windows::core::w!("zed-text-hash");
810pub const CLIPBOARD_METADATA_FORMAT: PCWSTR = windows::core::w!("zed-metadata");
811
812#[cfg(test)]
813mod tests {
814    use crate::{ClipboardItem, Platform, WindowsPlatform};
815
816    #[test]
817    fn test_clipboard() {
818        let platform = WindowsPlatform::new();
819        let item = ClipboardItem::new("你好".to_string());
820        platform.write_to_clipboard(item.clone());
821        assert_eq!(platform.read_from_clipboard(), Some(item));
822
823        let item = ClipboardItem::new("12345".to_string());
824        platform.write_to_clipboard(item.clone());
825        assert_eq!(platform.read_from_clipboard(), Some(item));
826
827        let item = ClipboardItem::new("abcdef".to_string()).with_metadata(vec![3, 4]);
828        platform.write_to_clipboard(item.clone());
829        assert_eq!(platform.read_from_clipboard(), Some(item));
830    }
831}