juicewrld-desktopsrc-taurisrcpluginsshared.rs
1.4.2Released Nov 21, 2026
shared.rs
57 lines2.4 KBRust//! WebView2 shared buffers (ICoreWebView2Environment12::CreateSharedBuffer): one block of memory that the page's//! script, this process and, through a duplicated handle, the plugin host all see. The page gets it as an ArrayBuffer//! (PostSharedBufferToScript, the `sharedbufferreceived` event on `chrome.webview`); the host maps the same file mapping.//! Everything here runs on the main thread, inside `Webview::with_webview`, where WebView2's objects live.use serde_json::Value;use tauri::webview::PlatformWebview;use webview2_com::Microsoft::Web::WebView2::Win32::{ ICoreWebView2Environment12, ICoreWebView2SharedBuffer, ICoreWebView2_17, COREWEBVIEW2_SHARED_BUFFER_ACCESS_READ_WRITE,};use windows::core::{Interface, HSTRING};use windows::Win32::Foundation::HANDLE;/// A shared buffer, kept open on the main thread until `close`.pub struct Shared { buffer: ICoreWebView2SharedBuffer, /// This process's view of the memory. pub ptr: *mut u8, pub len: usize, /// The file mapping behind it, owned by WebView2: duplicate it, never close it. pub mapping: HANDLE,}/// Makes a buffer of `len` bytes in the webview's environment (zeroed by Windows).////// # Safety/// On the main thread, with the webview `with_webview` handed over.pub unsafe fn create(w: &PlatformWebview, len: usize) -> windows::core::Result<Shared> { let env: ICoreWebView2Environment12 = w.environment().cast()?; let buffer = env.CreateSharedBuffer(len as u64)?; let mut ptr = std::ptr::null_mut(); buffer.Buffer(&mut ptr)?; let mut size = 0u64; buffer.Size(&mut size)?; let mut mapping = HANDLE::default(); buffer.FileMappingHandle(&mut mapping)?; Ok(Shared { buffer, ptr, len: size as usize, mapping })}/// Hands the buffer to the page's script, read and write, with `data` as the event's `additionalData`.////// # Safety/// As for `create`.pub unsafe fn post(w: &PlatformWebview, s: &Shared, data: &Value) -> windows::core::Result<()> { let core: ICoreWebView2_17 = w.controller().CoreWebView2()?.cast()?; core.PostSharedBufferToScript(&s.buffer, COREWEBVIEW2_SHARED_BUFFER_ACCESS_READ_WRITE, &HSTRING::from(data.to_string()))}impl Shared { /// Lets go of this process's view; the memory lasts while the page or the host still maps it. pub fn close(self) { // SAFETY: the buffer is WebView2's own object, used on the thread it was made on. unsafe { let _ = self.buffer.Close(); } }}