platform.rs

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