juicewrld-desktopsrc-taurisrcpluginstestpage.rs
1.4.2Released Nov 21, 2026
testpage.rs
138 lines5.9 KBRust//! The plugin test page, in debug builds only: a window of its own on `http://jwtest.localhost/`, served from//! `plugin-test/` on disk as the page asks for it (edit a file, reload the window), with the same plugin API the site//! gets (site.js, let in for this origin) and the same commands, granted to this one webview by a capability added while//! the app runs. A release build has none of it: this module, the protocol and the capability are compiled out.use std::path::Path;use tauri::http::{header, Request, Response, StatusCode};use tauri::ipc::CapabilityBuilder;use tauri::webview::PageLoadEvent;use tauri::{AppHandle, Manager, Runtime, WebviewUrl, WebviewWindowBuilder};pub use super::TEST_LABEL as LABEL;/// Where the page comes from.pub const ORIGIN: &str = "http://jwtest.localhost";const DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/plugin-test");/// The worklet, read from the source tree as the page loads it (so an edit shows on a reload).const WORKLET: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/src/plugins/worklet.js");/// Every command the site may call, the IPC measurements, and the menu's actions for scripted runs.const PERMISSIONS: &[&str] = &[ "allow-plugins-status", "allow-plugins-subscribe", "allow-plugins-request-enable", "allow-plugins-request-scan", "allow-plugins-list", "allow-plugins-unsupported", "allow-plugins-manage", "allow-plugins-open", "allow-plugins-close", "allow-plugins-editor", "allow-plugins-get-state", "allow-plugins-set-state", "allow-plugins-params", "allow-plugins-set-param", "allow-plugins-reset", "allow-plugins-bypass", "allow-plugins-stream", "allow-plugins-stream-close", "allow-plugins-render", "allow-plugins-bench-echo", "allow-plugins-bench-channel", "allow-plugins-test-action",];/// Serves the test page's files: names only (no folders, no `..`), from plugin-test/, and the worklet at the path the/// site gets it from.pub fn protocol<R: Runtime>(builder: tauri::Builder<R>) -> tauri::Builder<R> { builder.register_uri_scheme_protocol("jwtest", |_ctx, request| serve(&request))}fn serve(request: &Request<Vec<u8>>) -> Response<Vec<u8>> { let path = request.uri().path(); let bytes = if path == super::WORKLET_PATH { std::fs::read(WORKLET).ok() } else { let name = path.trim_start_matches('/'); let name = if name.is_empty() { "index.html" } else { name }; let plain = name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) && !name.starts_with('.'); if plain { std::fs::read(Path::new(DIR).join(name)).ok() } else { None } }; let Some(bytes) = bytes else { return Response::builder().status(StatusCode::NOT_FOUND).body(b"not found".to_vec()).unwrap_or_default(); }; let kind = match path.rsplit('.').next() { Some("html") => "text/html; charset=utf-8", Some("js") => "text/javascript; charset=utf-8", Some("css") => "text/css; charset=utf-8", Some("wav") => "audio/wav", _ => "application/octet-stream", }; // The site's own limits where they matter here: scripts from this origin only, and no fetch to the IPC protocol // unless the page asks (`?ipc=fetch`, to measure that path too), so IPC falls back to postMessage as on the site. let ipc = request.uri().query().is_some_and(|q| q.contains("ipc=fetch")); let connect = if ipc { "connect-src 'self' ipc: http://ipc.localhost" } else { "connect-src 'self'" }; let csp = format!("default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; worker-src 'self' blob:; {connect}"); Response::builder() .header(header::CONTENT_TYPE, kind) .header(header::CACHE_CONTROL, "no-store") .header("Content-Security-Policy", csp) .body(bytes) .unwrap_or_default()}/// Opens the test window, or brings it forward. A quiet test run (JW_NO_FOCUS) opens it without taking focus, behind/// the other windows, and (JW_MUTE) muted.pub fn open(app: &AppHandle) -> tauri::Result<()> { let quiet = crate::test_switch("JW_NO_FOCUS"); if let Some(w) = app.get_webview_window(LABEL) { if quiet { return Ok(()); } let _ = w.unminimize(); return w.set_focus(); } // A page on one of the app's own protocols counts as local to Tauri's access control. let mut cap = CapabilityBuilder::new("plugin-test").local(true).webview(LABEL); for p in PERMISSIONS { cap = cap.permission(*p); } app.add_capability(cap)?; let url = format!("{ORIGIN}/index.html").parse().expect("test page url"); let load_app = app.clone(); let window = WebviewWindowBuilder::new(app, LABEL, WebviewUrl::CustomProtocol(url)) .title("Plugin test (debug build)") .inner_size(1120.0, 860.0) // The same options as the app's other webviews, which share its WebView2 profile. .additional_browser_args(crate::BROWSER_ARGS) .focused(!quiet) .initialization_script(super::site_script(Some(ORIGIN))) .on_page_load(move |_, payload| { if matches!(payload.event(), PageLoadEvent::Started) { super::page_changed(&load_app, LABEL); } }) .build()?; let _ = window.with_webview(|w| unsafe { if let Ok(core) = w.controller().CoreWebView2() { crate::mute_for_test(&core, "test page"); } }); if quiet { if let Ok(h) = window.hwnd() { crate::to_back(h.0 as isize); } } // Closed: its instances go with it, as with a page that loads anew. let close_app = app.clone(); window.on_window_event(move |e| { if let tauri::WindowEvent::Destroyed = e { super::page_changed(&close_app, LABEL); } }); Ok(())}