juicewrld-desktopsrc-taurisrcpluginsmod.rs
1.4.2Released Nov 21, 2026
mod.rs
2,281 lines103.6 KBRust//! The user's own plugins in the site's studio. A browser can't run native plugins; this app can, in a process of its//! own (juicewrld-plugins.exe, host/), and hands the page what it needs to put them in the studio's mixer slots://! commands for the plugins found, their instances, editors, state and parameters, and an audio path through shared//! memory between the page's AudioWorklet and the host (ring.rs).//!//! Nothing happens until the user turns on "Use my plugins in the studio" in the title bar's menu (or answers the//! bar's prompt when the page asks for it): no scan, no module loaded, every command but `plugins_status` refused.//! Turning it on starts the first scan of the plugin folders (folders.rs: the standard places, FL Studio's, the//! user's own, each with a tick). After that a quick check runs in the background when the app starts and when the//! studio asks for the list: the folders are listed and compared with the cache, and only what's new or changed is//! read, a module without a moduleinfo.json loaded in a scan child one at a time, a module that failed (a licence//! window, usually) never loaded again until its file changes or the user presses Try again (scan.rs has why). The page//! names plugins by the IDs the scan gave and nothing else; it never passes a path, and the host loads only modules//! inside the plugin folders (proto::module_allowed). The site's webview on https://juicewrld.io may call these//! commands (capabilities/site.json), and in debug builds the test page (testpage.rs); each command checks its caller//! again, and an instance belongs to the page that opened it and is closed when that page goes.//!//! The user manages their plugins in the plugin manager (manager.rs), a window of the app's own like FL Studio's: the//! list with favourites and Hide, the folders with their ticks, every kind of scan. The title bar's menu keeps the//! switch, Scan for plugins and Manage plugins…; the page can open the manager (`plugins_manage`) and nothing more.pub mod folders;pub mod host;pub mod manager;// The plugin files' headers, read from disk (scan.rs), never loaded.pub mod pe;// Shared with the host (host/main.rs includes them too), so each binary uses part of them.pub mod proto;pub mod ring;pub mod scan;pub mod shared;pub mod testpage;use proto::{Event, Opened, Request};use serde::{Deserialize, Serialize};use serde_json::{json, Value};use std::cell::RefCell;use std::collections::{BTreeMap, HashMap, HashSet};use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{mpsc, Arc, Mutex, MutexGuard};use std::time::{Duration, Instant};use tauri::ipc::{Channel, InvokeBody, Response};use tauri::menu::{CheckMenuItem, Menu, MenuItem, PredefinedMenuItem};use tauri::{AppHandle, LogicalPosition, Manager, Url, Webview};/// The page API's version, as `status().api` gives it. 2: `manage()` opens the plugin manager, and the list marks the/// user's favourites. (site.js `juicewrldDesktop.plugins.version` stays 1: every call of version 1 is there as it was.)pub const API_VERSION: u32 = 2;/// The test page's webview (debug builds only, but named here so the permission check can be tested in any build).pub const TEST_LABEL: &str = "plugin-test";/// Where the page loads the AudioWorklet from (same origin, so the site's CSP lets it); the app answers it.pub const WORKLET_PATH: &str = "/__juicewrld-desktop/plugins-worklet-1.js";pub const WORKLET_JS: &str = include_str!("worklet.js");const OFF: &str = "plugins are off: turn on Use my plugins in the studio in the app's menu";/// How long a scan child may take to load one module before it's ended and the module marked "Needs activation, or/// didn't load". Long enough for a big shell module (Waves' takes about 10 s), short enough that a licence window/// isn't left on the screen for long.const LOAD_LIMIT: Duration = Duration::from_secs(30);/// How long a window a module opens as it loads may stay before the scan ends it (a licence or activation window,/// almost always): long enough that a splash screen that goes by itself is let be, short enough that the window only/// flashes by. Not for Try again, which is the user asking for that one module: it gets the whole LOAD_LIMIT.const WINDOW_GRACE: Duration = Duration::from_secs(2);/// What the app calls a module that couldn't be read.const UNREAD: &str = "Needs activation, or didn't load";/// The quick check runs at most this often when the studio asks for the list (it only lists folders unless something/// is new, but a page asking in a loop shouldn't keep the disk busy).const QUICK_EVERY: Duration = Duration::from_secs(15);/// How long after start-up the quick check waits, so it never slows the window opening.const STARTUP_DELAY: Duration = Duration::from_secs(4);/// Under the plugin manager's list and folders, where it names the format (Steinberg's usage guidelines ask for the/// notice wherever the name is used).const TRADEMARK: &str = "VST is a registered trademark of Steinberg Media Technologies GmbH";/// Instances one page may have open at once: far more than a mix needs, few enough that a page gone wrong can't fill/// the PC's memory with plugins.const MAX_INSTANCES: usize = 256;fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(|e| e.into_inner())}/// What's kept with the app's settings (plugins.json beside the window state).pub struct Settings { pub enabled: bool, /// Folders the user added, scanned along with the default ones. pub folders: Vec<String>, /// Folders the user unticked (default or added), compared without case: listed, not scanned. pub unticked: Vec<String>, /// Where each plugin's editor was last left (screen pixels), by plugin ID. pub editors: BTreeMap<String, [i32; 2]>, /// Plugins (by ID) and vendors (by name) the user hid from the studio's list. pub hidden_plugins: Vec<String>, pub hidden_vendors: Vec<String>, /// Plugins (by ID) the user starred in the plugin manager: the studio's add-effect menu lists them first. pub favourites: Vec<String>,}/// The settings file in `dir` (plugins.json), or the defaults (plugins off) when there's none or it can't be read.fn read_settings(dir: &Path) -> Settings { std::fs::read(dir.join("plugins.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()}/// Saves the settings in `dir` (plugins.json), through a temporary file so a crash never leaves half a file.fn write_settings(dir: &Path, s: &Settings) { let _ = std::fs::create_dir_all(dir); let tmp = dir.join("plugins.json.tmp"); if let Ok(bytes) = serde_json::to_vec_pretty(s) { if std::fs::write(&tmp, bytes).is_ok() { let _ = std::fs::rename(&tmp, dir.join("plugins.json")); } }}/// A plugin as the page lists it (`plugins_list`): what the scan found, and whether the user starred it (only said when/// they did).pub struct ListedPlugin { pub plugin: scan::Plugin, pub favourite: bool,}/// The plugins the page may list: what the scan found, less what the user hid (by itself or with its vendor), in the/// scan's order (effects first), each marked when it's a favourite.pub fn visible_list(found: &[scan::Found], s: &Settings) -> Vec<ListedPlugin> { found .iter() .map(|f| &f.plugin) .filter(|p| !scan::is_hidden(p, &s.hidden_plugins, &s.hidden_vendors)) .map(|p| ListedPlugin { plugin: p.clone(), favourite: s.favourites.iter().any(|id| id.eq_ignore_ascii_case(&p.id)) }) .collect()}/// Puts `item` on the list or takes it off (compared without case), as `on` says; true when that changed the list.fn set_in(list: &mut Vec<String>, item: &str, on: bool) -> bool { let at = list.iter().position(|x| x.eq_ignore_ascii_case(item)); match (at, on) { (None, true) => list.push(item.to_string()), (Some(i), false) => { list.remove(i); } _ => return false, } true}/// Ticks a listed folder (it's scanned) or unticks it (listed, not scanned), compared as Windows compares paths; true/// when that changed anything.fn set_ticked(s: &mut Settings, path: &str, on: bool) -> bool { let same = |u: &String| folders::norm(Path::new(u)) == folders::norm(Path::new(path)); let was_on = !s.unticked.iter().any(same); if was_on == on { return false; } if on { s.unticked.retain(|u| !same(u)); } else { s.unticked.push(path.to_string()); } true}/// A question in the title bar, answered there (out of the page's reach).enum Ask { /// Turn plugins on (and scan, the first time). Enable, /// Scan for plugins now. Scan,}/// Why a scan runs, which decides what the bar says about it.pub enum Trigger { /// The user asked: Scan for plugins, a folder added or ticked, Try again. The bar says what was found. User, /// The user turned plugins on: the first full scan, or a quick check after. TurnedOn, /// The quick check at start-up or when the studio asks for the list: the bar speaks only when it added plugins /// (or found one that needs activation), and while a module loads. Quick,}/// What a scan reads. Always one module at a time, and never anything outside the folders ticked.pub enum Mode { /// What's new or changed since the last scan: the quick check, Scan for plugins, a folder added or ticked. Changed, /// Try again on one module that failed (its path, as the cache keys it): it loads with the whole LOAD_LIMIT and no /// window rule, since the user asked for it and is there to deal with its activation window. TryAgain(String), /// Retry failed (the plugin manager): every module that failed loads again, the window rule standing (Try again on /// one gives it the time), as well as what's new or changed. Failed, /// Rescan everything (the plugin manager): every module that read fine is read again (`for_rescan`); what failed /// stays failed (Retry failed is for those). Everything,}/// The stamp "Rescan everything" gives the modules it reads again. No file has it (no size is that big), so the scan/// takes each for a module that changed.const RESCAN: scan::Stamp = scan::Stamp { modified: 0, size: u64::MAX };/// The last scan's cache with every module that read fine marked as changed (RESCAN), so the scan reads each one again/// as it reads a changed module: from its moduleinfo.json where it has one, else in a scan child, one at a time, the/// window rule standing. A module that failed is left as it is, an older copy stays a copy, and a module whose every/// plugin is hidden still isn't loaded. Until a module is read again its entry stands, so a rescan stopped half way/// loses nothing (`restore_stamps` then puts back the stamps of what wasn't read).fn for_rescan(cache: &scan::Cache) -> scan::Cache { let mut c = cache.clone(); for m in c.modules.values_mut().filter(|m| m.error.is_none() && m.copy_of.is_none()) { m.stamp = RESCAN; } c}/// After a rescan: the modules it didn't read again (it was stopped, or kept them as hidden) get their own stamps back,/// so the next quick check doesn't take them for changed.fn restore_stamps(cache: &mut scan::Cache, old: &scan::Cache) { for (k, m) in cache.modules.iter_mut().filter(|(_, m)| m.stamp == RESCAN) { if let Some(o) = old.modules.get(k) { m.stamp = o.stamp; } }}/// What a scan in `mode` loads besides the new and changed: `retry` (failed modules to load again) and `patient` (those/// that load without the window rule: the one the user pressed Try again on).fn retry_sets(mode: &Mode, old: &scan::Cache, roots: &[PathBuf]) -> (HashSet<String>, HashSet<String>) { match mode { Mode::TryAgain(path) => ([path.clone()].into(), [path.clone()].into()), Mode::Failed => (scan::unread(&scan::only_under(old, roots)).into_iter().map(|u| u.path).collect(), HashSet::new()), Mode::Changed | Mode::Everything => (HashSet::new(), HashSet::new()), }}/// How long a window a module opens as it loads may stay: WINDOW_GRACE, unless it's the module the user asked for.fn window_rule(patient: &HashSet<String>, module: &Path) -> Option<Duration> { let asked = patient.iter().any(|r| scan::same_path(r) == scan::same_path(&module.to_string_lossy())); if asked { None } else { Some(WINDOW_GRACE) }}/// A folder as the menu lists it.pub struct Listed { pub folder: folders::Folder, /// Ticked: scanned. pub on: bool, /// The user added it (so they can remove it). pub added: bool, /// It's there (a folder the user added can go missing; a default one that doesn't exist isn't listed). pub exists: bool,}struct Inst { owner: String, generation: u32, host: u32, id: String, name: String, label: String, rate: f64, block: u32, stream: Option<u64>,}struct State { settings: Settings, found: Vec<scan::Found>, /// Modules that couldn't be read, remembered until they change or the user presses Try again. unread: Vec<scan::Unread>, /// Plugins in the folders that can't run here, listed greyed. unsupported: Vec<scan::Unsupported>, /// The default folders on this PC, as last discovered (folders.rs), refreshed for each scan and each menu. defaults: Option<Vec<folders::Folder>>, /// When the last scan or quick check ended, for QUICK_EVERY. last_check: Option<Instant>, /// The last scan (from the cache file, across runs), if there ever was one. stats: Option<scan::Stats>, scanning: bool, progress: Option<scan::Progress>, instances: BTreeMap<u32, Inst>, next: u32, next_stream: u64, channels: HashMap<String, Channel<Value>>, /// Pages that answered the bar's prompt with "Not now"; they aren't asked again until they load anew. declined: HashSet<String>, /// Each webview's document, counted up as it loads anew: an open that was under way when its page went doesn't /// leave its instance behind for the next page. pages: HashMap<String, u64>, /// The question in the bar, and who's waiting for its answer. asking: Option<(Ask, Vec<mpsc::Sender<bool>>)>, /// Pages waiting for the scan under way to end. scan_waiters: Vec<mpsc::Sender<bool>>, /// The plugin manager's window, listening (manager.rs): it hears every change and reads its state again. manager: Option<Channel<Value>>,}pub struct Plugins { dir: PathBuf, state: Mutex<State>, /// Set to stop the scan under way (the menu's Stop scanning, plugins switched off, the app closing). stop_scan: Arc<AtomicBool>, host: host::Host,}/// The scan file: the module cache and what the last scan did, so a new run knows whether there ever was one.struct ScanFile { cache: scan::Cache, last: Option<LastScan>,}struct LastScan { millis: u64, at: u64, read: usize, loaded: usize,}thread_local! { /// The streams' shared buffers, kept on the main thread where WebView2 made them. static STREAMS: RefCell<HashMap<u64, shared::Shared>> = RefCell::new(HashMap::new());}/// The host's binary, beside the app's.fn host_exe() -> PathBuf { std::env::current_exe().map(|p| p.with_file_name("juicewrld-plugins.exe")).unwrap_or_default()}/// Whether this copy of the app can run plugins: the installed app has the host beside it; the portable exe doesn't.pub fn supported() -> bool { host_exe().is_file()}/// site.js as a webview gets it: the plugin API switched on when this copy can run plugins, and the test page's origin/// let in too when given (debug builds).pub fn site_script(test_origin: Option<&str>) -> String { let mut s = include_str!("../site.js").replace("/*JW_PLUGINS*/ false", if supported() { "true" } else { "false" }); if let Some(origin) = test_origin { s = s.replace("/*JW_TEST_ORIGIN*/ \"\"", &format!("{origin:?}")); } s}/// Who may use the plugins: the site's own webview on https://juicewrld.io, and in debug builds the test page.pub fn allowed_caller(label: &str, url: &Url, debug: bool) -> bool { let site = label == "site" && url.scheme() == "https" && url.host_str() == Some("juicewrld.io") && url.port().is_none(); let test = debug && label == TEST_LABEL && url.scheme() == "http" && url.host_str() == Some("jwtest.localhost"); site || test}fn caller(webview: &Webview) -> Result<String, String> { let url = webview.url().map_err(|_| "no page".to_string())?; if allowed_caller(webview.label(), &url, cfg!(debug_assertions)) { Ok(webview.label().to_string()) } else { Err("plugins aren't available to this page".into()) }}/// A plugin ID as the scan gives them: 32 hex digits, nothing else (and never a path).pub fn valid_id(id: &str) -> bool { id.len() == 32 && id.bytes().all(|b| b.is_ascii_hexdigit())}/// The window title's label from the page: short, one line.pub fn clean_label(label: &str) -> String { let s: String = label.chars().filter(|c| !c.is_control()).take(60).collect(); s.trim().to_string()}fn layout_name(o: &Opened) -> String { match (o.inputs, o.outputs) { (2, 2) => "stereo".into(), (1, 1) => "mono".into(), (1, 2) => "mono-to-stereo".into(), (0, _) => "instrument".into(), (i, o) => format!("{i}-to-{o}"), }}/// Debug builds only: plugin folders to scan instead of the standard ones (JW_PLUGINS_FOLDERS, separated by `;`), so a/// test run never looks at the plugins installed on the PC it runs on.fn folders_override() -> Option<Vec<PathBuf>> { let v = std::env::var("JW_PLUGINS_FOLDERS").ok()?; Some(v.split(';').map(str::trim).filter(|s| !s.is_empty()).map(PathBuf::from).collect())}fn folders_override() -> Option<Vec<PathBuf>> { None}/// Debug builds: a run with plugin folders of its own (JW_PLUGINS_FOLDERS) has the host and the scan children refuse any/// module outside them (JW_PLUGINS_ONLY_UNDER, checked in host/main.rs before anything loads), unless the run named/// those folders itself. A second lock on the same door: the app already asks only for modules in the folders.pub fn child_env(cmd: &mut std::process::Command) { if std::env::var_os("JW_PLUGINS_ONLY_UNDER").is_none() { if let Some(f) = folders_override() { let only: Vec<String> = f.iter().map(|p| p.to_string_lossy().to_string()).collect(); cmd.env("JW_PLUGINS_ONLY_UNDER", only.join(";")); } } let _ = cmd;}/// The default folders: those on this PC (folders.rs), or in a debug run with JW_PLUGINS_FOLDERS that run's own and/// nothing else (no registry, no FL Studio, no standard place is even looked at).fn discover_defaults() -> Vec<folders::Folder> { match folders_override() { Some(f) => f.into_iter().map(|path| folders::Folder { path, kind: folders::Kind::Test, from: "this test run's own" }).collect(), None => folders::defaults(&folders::Windows), }}/// The list as the menu shows it: the defaults, then the folders the user added (each once), with their ticks.pub fn folder_list(defaults: &[folders::Folder], s: &Settings) -> Vec<Listed> { let unticked = |p: &Path| s.unticked.iter().any(|u| folders::norm(Path::new(u)) == folders::norm(p)); let mut out: Vec<Listed> = defaults.iter().map(|f| Listed { folder: f.clone(), on: !unticked(&f.path), added: false, exists: true }).collect(); for a in &s.folders { let path = PathBuf::from(a); if out.iter().any(|l| folders::norm(&l.folder.path) == folders::norm(&path)) { continue; } let on = !unticked(&path); out.push(Listed { folder: folders::Folder { path: path.clone(), kind: folders::Kind::Added, from: "added by the user" }, on, added: true, exists: path.is_dir() }); } out}/// The folders scanned: those listed, ticked and there.pub fn ticked(list: &[Listed]) -> Vec<PathBuf> { list.iter().filter(|l| l.on && l.exists).map(|l| l.folder.path.clone()).collect()}impl Plugins { pub fn new(app: &AppHandle) -> Plugins { let dir = app.path().app_config_dir().unwrap_or_else(|_| std::env::temp_dir().join("juicewrld.io")); // A debug build's test runs keep their plugin settings and scan apart from the installed app's. let dir = crate::debug_config_dir().unwrap_or(dir); let settings = read_settings(&dir); if let Some(f) = folders_override() { eprintln!("[plugins] debug run: plugin folders are {f:?} only"); } let events_app = app.clone(); let gone_app = app.clone(); let host = host::Host::new( host_exe(), Arc::new(move |generation, ev| on_host_event(&events_app, generation, ev)), Arc::new(move |gone| on_host_gone(&gone_app, gone)), ); let p = Plugins { dir, state: Mutex::new(State { settings, found: Vec::new(), unread: Vec::new(), unsupported: Vec::new(), defaults: None, last_check: None, stats: None, scanning: false, progress: None, instances: BTreeMap::new(), next: 1, next_stream: 1, channels: HashMap::new(), declined: HashSet::new(), pages: HashMap::new(), asking: None, scan_waiters: Vec::new(), manager: None, }), stop_scan: Arc::new(AtomicBool::new(false)), host, }; // What the last scan found is listed from its file at once. Nothing is scanned or loaded here (startup() runs // the quick check a moment later, when plugins are on). p.load_found(); p } /// The plugins, failures and greyed plugins the cache file knows, and when it was made. fn load_found(&self) { if let Some(f) = self.load_scan_file().filter(|f| f.cache.version == scan::CACHE_VERSION) { self.take_cache(&f.cache, f.last.as_ref()); } } /// The lists from a cache (a scan's result, or one of its checkpoints), with `last` saying when its scan ran. fn take_cache(&self, cache: &scan::Cache, last: Option<&LastScan>) { // Only what's under the folders ticked now: the cache also remembers modules in folders unticked for a while. let cache = &scan::only_under(cache, &self.roots()); let found = scan::plugins(cache); let unread = scan::unread(cache); let unsupported = scan::unsupported(cache); let mut st = lock(&self.state); if let Some(l) = last { st.stats = Some(scan::Stats { modules: cache.modules.len(), plugins: found.len(), effects: found.iter().filter(|x| x.plugin.kind == "effect").count(), instruments: found.iter().filter(|x| x.plugin.kind == "instrument").count(), read: l.read, loaded: l.loaded, failed: unread.len(), unsupported: unsupported.len(), stopped: false, millis: l.millis, at: l.at, }); } st.found = found; st.unread = unread; st.unsupported = unsupported; } /// The default folders, discovered the first time they're needed. fn defaults(&self) -> Vec<folders::Folder> { if let Some(d) = lock(&self.state).defaults.clone() { return d; } self.rediscover() } /// Looks for the default folders again (a DAW installed since adds its own): registry reads and folder listings. fn rediscover(&self) -> Vec<folders::Folder> { let t0 = Instant::now(); let d = discover_defaults(); let ms = t0.elapsed().as_millis(); let mut st = lock(&self.state); if st.defaults.as_ref() != Some(&d) { eprintln!("[plugins] plugin folders ({ms} ms): {:?}", d.iter().map(|f| format!("{} [{}]", f.path.display(), f.kind.label())).collect::<Vec<_>>()); } st.defaults = Some(d.clone()); d } fn listed(&self) -> Vec<Listed> { let defaults = self.defaults(); folder_list(&defaults, &lock(&self.state).settings) } fn save_settings(&self, s: &Settings) { write_settings(&self.dir, s); } fn cache_path(&self) -> PathBuf { self.dir.join("plugin-scan.json") } fn load_scan_file(&self) -> Option<ScanFile> { std::fs::read(self.cache_path()).ok().and_then(|b| serde_json::from_slice(&b).ok()) } fn save_scan_file(&self, f: &ScanFile) { let _ = std::fs::create_dir_all(&self.dir); if let Ok(bytes) = serde_json::to_vec(f) { let tmp = self.cache_path().with_extension("tmp"); if std::fs::write(&tmp, bytes).is_ok() { let _ = std::fs::rename(&tmp, self.cache_path()); } } } /// The folders scanned and the only ones modules are loaded from: listed, ticked, there. fn roots(&self) -> Vec<PathBuf> { ticked(&self.listed()) } fn enabled(&self) -> bool { lock(&self.state).settings.enabled } /// The plugins the page may list: what the scan found, less what the user hid, favourites marked. fn visible(st: &State) -> Vec<ListedPlugin> { visible_list(&st.found, &st.settings) } fn status(&self) -> Value { let s = lock(&self.state); if !s.settings.enabled { // Off: whether plugins can be used, and that they're off; nothing about what's installed on this PC. return json!({ "api": API_VERSION, "supported": self.host.exe_present(), "enabled": false }); } json!({ "api": API_VERSION, "supported": self.host.exe_present(), "enabled": s.settings.enabled, // Whether a scan ever ran: none has until the user presses Scan for plugins. "scanned": s.stats.is_some(), "scanning": s.scanning, "progress": s.progress, "plugins": Self::visible(&s).len(), "hidden": s.found.len() - Self::visible(&s).len(), "unread": s.unread.len(), // Found in the folders but can't run here (old format, 32-bit, ARM): plugins_unsupported lists them. "unsupported": s.unsupported.len(), "scan": s.stats, }) } /// Sends `ev` to every page listening, and to the plugin manager (which reads its state again). fn broadcast(&self, ev: Value) { let st = lock(&self.state); for ch in st.channels.values() { let _ = ch.send(ev.clone()); } if let Some(m) = &st.manager { let _ = m.send(ev); } } /// Tells the plugin manager something changed that the pages don't need to hear (a folder ticked while plugins are /// off, say): it reads its state again. fn tell_manager(&self) { if let Some(m) = &lock(&self.state).manager { let _ = m.send(json!({ "type": "changed" })); } } fn send_to(&self, owner: &str, ev: Value) { if let Some(ch) = lock(&self.state).channels.get(owner) { let _ = ch.send(ev); } } /// The instance `id` of page `owner`, with the host that runs it. fn instance(&self, owner: &str, id: u32) -> Result<(Arc<host::Conn>, u32), String> { let st = lock(&self.state); if !st.settings.enabled { return Err(OFF.into()); } let i = st.instances.get(&id).filter(|i| i.owner == owner).ok_or("no such instance")?; let conn = self.host.current().filter(|c| c.generation == i.generation).ok_or("this instance was lost")?; Ok((conn, i.host)) }}/// Runs blocking work (waiting on the host) off the async runtime's threads.async fn blocking<T: Send + 'static>(f: impl FnOnce() -> Result<T, String> + Send + 'static) -> Result<T, String> { tauri::async_runtime::spawn_blocking(f).await.map_err(|e| e.to_string())?}fn owner_window(app: &AppHandle) -> u64 { app.get_window("main").and_then(|w| w.hwnd().ok()).map(|h| h.0 as usize as u64).unwrap_or(0)}/// The bytes of a raw invoke body: an ArrayBuffer through the IPC protocol, or a JSON array of numbers where the page's/// CSP sends IPC through postMessage instead (the site's does).fn body_bytes(body: &InvokeBody) -> Result<Vec<u8>, String> { match body { InvokeBody::Raw(b) => Ok(b.clone()), InvokeBody::Json(Value::Array(a)) => { a.iter().map(|v| v.as_u64().filter(|&n| n < 256).map(|n| n as u8).ok_or_else(|| "expected bytes".to_string())).collect() } _ => Err("expected bytes".into()), }}fn header_u32(req: &tauri::ipc::Request<'_>, name: &str) -> Result<u32, String> { req.headers() .get(name) .and_then(|v| v.to_str().ok()) .and_then(|v| v.parse().ok()) .ok_or_else(|| format!("missing {name}"))}// ---- events from the host ----fn on_host_event(app: &AppHandle, generation: u32, ev: Event) { let p = app.state::<Plugins>(); let inst_of = |host_inst: u32| -> Option<(u32, String, String)> { let st = lock(&p.state); st.instances.iter().find(|(_, i)| i.generation == generation && i.host == host_inst).map(|(id, i)| (*id, i.owner.clone(), i.id.clone())) }; match ev { Event::Latency { inst, samples } => { if let Some((id, owner, _)) = inst_of(inst) { p.send_to(&owner, json!({ "type": "latency", "instance": id, "latency": samples })); } } Event::Param { inst, id: param, value, phase } => { if let Some((id, owner, _)) = inst_of(inst) { p.send_to(&owner, json!({ "type": "param", "instance": id, "id": param, "value": value, "phase": phase })); } } Event::Editor { inst, open, x, y } => { if let Some((id, owner, plugin)) = inst_of(inst) { let settings = { let mut st = lock(&p.state); st.settings.editors.insert(plugin, [x, y]); st.settings.clone() }; p.save_settings(&settings); if !open { p.send_to(&owner, json!({ "type": "editor", "instance": id, "open": false })); } } } Event::Changed { inst, flags } => { if let Some((id, owner, _)) = inst_of(inst) { p.send_to(&owner, json!({ "type": "changed", "instance": id, "flags": flags })); } } Event::OpenEditor { inst } => { if let Some((id, owner, _)) = inst_of(inst) { p.send_to(&owner, json!({ "type": "editor-requested", "instance": id })); } } Event::Heartbeat { .. } => {} }}/// The host went: its instances are lost. Their pages hear which ones and why, their streams are marked lost (the/// worklet goes silent at once), and the host starts again for whatever the page opens next.fn on_host_gone(app: &AppHandle, gone: host::Gone) { let p = app.state::<Plugins>(); let (lost, enabled) = { let mut st = lock(&p.state); let ids: Vec<u32> = st.instances.iter().filter(|(_, i)| i.generation == gone.generation).map(|(id, _)| *id).collect(); let lost: Vec<(u32, Inst)> = ids.into_iter().filter_map(|id| st.instances.remove(&id).map(|i| (id, i))).collect(); (lost, st.settings.enabled) }; let crashed_in = gone.crash.as_ref().and_then(|c| c["inst"].as_u64()).map(|n| n as u32); let mut by_owner: HashMap<String, Vec<Value>> = HashMap::new(); for (id, i) in &lost { if let Some(sid) = i.stream { close_stream(app, sid, ring::STATE_LOST); } by_owner.entry(i.owner.clone()).or_default().push(json!({ "instance": id, "id": i.id, "name": i.name, "label": i.label, "culprit": crashed_in == Some(i.host) })); } let code = gone.crash.as_ref().and_then(|c| c["code"].as_str().map(str::to_string)); for (owner, instances) in by_owner { p.send_to(&owner, json!({ "type": "lost", "reason": gone.reason, "code": code, "instances": instances })); } if gone.reason == "crashed" || gone.reason == "hung" { let culprit = lost.iter().find(|(_, i)| crashed_in == Some(i.host)).map(|(_, i)| i.name.clone()); let msg = match (gone.reason.as_str(), culprit) { ("crashed", Some(name)) => format!("{name} crashed; the studio's other plugins were reloaded"), ("crashed", None) => "A plugin crashed; the studio's plugins were reloaded".to_string(), (_, Some(name)) => format!("{name} stopped responding; the studio's other plugins were reloaded"), _ => "A plugin stopped responding; the studio's plugins were reloaded".to_string(), }; crate::bar_call(app, "notice", json!(msg)); // Ready for the next open, unless hosts keep dying. if enabled && p.host.may_restart() { let app = app.clone(); std::thread::spawn(move || { std::thread::sleep(Duration::from_millis(300)); let p = app.state::<Plugins>(); let roots: Vec<String> = p.roots().iter().map(|r| r.to_string_lossy().to_string()).collect(); if let Err(e) = p.host.connect(&roots, owner_window(&app)) { eprintln!("[plugins] couldn't restart the plugin host: {e}"); } }); } }}// ---- streams (main thread) ----fn close_stream(app: &AppHandle, sid: u64, state: u32) { let _ = app.run_on_main_thread(move || { STREAMS.with(|m| { if let Some(s) = m.borrow_mut().remove(&sid) { // SAFETY: the app's own view of the buffer, valid until close(). let ring = unsafe { ring::Ring::new(s.ptr, s.len) }; ring.set(ring::at::STATE, state); s.close(); } }) });}/// Duplicates a handle of this process into the host's.fn give_handle(process: isize, handle: windows::Win32::Foundation::HANDLE) -> Result<u64, String> { use windows::Win32::Foundation::{DuplicateHandle, DUPLICATE_SAME_ACCESS, HANDLE}; use windows::Win32::System::Threading::GetCurrentProcess; let mut out = HANDLE::default(); // SAFETY: duplicating WebView2's file mapping into the host process we started; the host closes its copy. unsafe { DuplicateHandle(GetCurrentProcess(), handle, HANDLE(process as *mut _), &mut out, 0, false, DUPLICATE_SAME_ACCESS) } .map_err(|e| format!("couldn't share the stream with the plugin host: {e}"))?; Ok(out.0 as usize as u64)}// ---- turning plugins on and off, scanning ----/// Plugins on or off. Turning them on starts a scan: the first full one (the bar says a plugin may show its licence/// window the first time), or a quick check of what changed since the last.pub fn set_enabled(app: &AppHandle, on: bool) { let p = app.state::<Plugins>(); let (settings, waiting) = { let mut st = lock(&p.state); if st.settings.enabled == on { return; } st.settings.enabled = on; let waiting = match (on, &st.asking) { (true, Some((Ask::Enable, _))) => st.asking.take().map(|(_, w)| w), _ => None, }; (st.settings.clone(), waiting) }; p.save_settings(&settings); for w in waiting.into_iter().flatten() { let _ = w.send(true); } crate::bar_call(app, "ask", Value::Null); if on { eprintln!("[plugins] turned on"); p.load_found(); start_scan(app, Mode::Changed, Trigger::TurnedOn); } else { eprintln!("[plugins] turned off"); p.stop_scan.store(true, Ordering::SeqCst); let lost: Vec<(u32, Inst)> = std::mem::take(&mut lock(&p.state).instances).into_iter().collect(); p.host.stop("stopped"); let mut by_owner: HashMap<String, Vec<Value>> = HashMap::new(); for (id, i) in lost { if let Some(sid) = i.stream { close_stream(app, sid, ring::STATE_LOST); } by_owner.entry(i.owner.clone()).or_default().push(json!({ "instance": id, "id": i.id, "name": i.name, "label": i.label, "culprit": false })); } for (owner, instances) in by_owner { p.send_to(&owner, json!({ "type": "lost", "reason": "off", "code": null, "instances": instances })); } crate::bar_call(app, "notice", json!("Plugins are off")); } p.broadcast(json!({ "type": "status", "status": p.status() }));}/// The app has started: with plugins on, a quick check runs in the background a moment later (unless the studio's/// list() has had one run meanwhile; nothing at all while they're off).pub fn startup(app: &AppHandle) { if !app.state::<Plugins>().enabled() { return; } let app = app.clone(); std::thread::spawn(move || { std::thread::sleep(STARTUP_DELAY); quick_check_soon(&app); });}/// "3 new plugins", "1 new plugin".fn count(n: usize, one: &str, many: &str) -> String { format!("{n} {}", if n == 1 { one } else { many })}/// A scan (scan.rs): the folders listed and compared with the cache, then what's new or changed read, a module without/// a moduleinfo.json loaded in a scan child of its own, one at a time; `mode` adds failed modules to load again (Try/// again on one, Retry failed) or has every module read again (Rescan everything). While a module loads the bar says/// which, so a licence window that opens can be put down to its plugin. The cache is saved after each module, and the/// pages and the plugin manager hear the list grow as it does. `trigger` says why it runs (what the bar says at the/// end); a scan already under way is left to finish.pub fn start_scan(app: &AppHandle, mode: Mode, trigger: Trigger) { let p = app.state::<Plugins>(); let first = { let mut st = lock(&p.state); if st.scanning || !st.settings.enabled || !p.host.exe_present() { return; } st.scanning = true; st.progress = None; st.stats.is_none() }; p.stop_scan.store(false, Ordering::SeqCst); p.broadcast(json!({ "type": "status", "status": p.status() })); if first { crate::bar_call(app, "notice", json!({ "text": "Looking for plugins. One may show its licence window the first time.", "stay": true })); } // A first scan that the quick check runs (the app closed during the first one) reports like the first. let trigger = if first && trigger == Trigger::Quick { Trigger::TurnedOn } else { trigger }; let app = app.clone(); std::thread::spawn(move || { let p = app.state::<Plugins>(); // Each scan looks for the default folders again: a DAW installed since adds its own. p.rediscover(); let roots = p.roots(); eprintln!("[plugins] scan ({trigger:?}, {mode:?}) in {roots:?}"); let old_file = p.load_scan_file(); let last = old_file.as_ref().and_then(|f| f.last.clone()); let old = old_file.map(|f| f.cache).unwrap_or_default(); let (retry, patient) = retry_sets(&mode, &old, &roots); // Rescan everything: the scan takes every module that read fine for changed (the real cache stays `old`). let base = if mode == Mode::Everything { for_rescan(&old) } else { old.clone() }; // What the lists showed before, for "3 new plugins" (the cache also remembers folders unticked for now). let shown_before = scan::only_under(&old, &roots); let before: HashSet<String> = scan::plugins(&shown_before).into_iter().map(|f| f.cid).collect(); let unread_before = scan::unread(&shown_before).len(); let exe = host_exe(); let stop = p.stop_scan.clone(); let loads = std::cell::Cell::new(0usize); let mut load = |m: &Path| { loads.set(loads.get() + 1); // A module that opens a window as it loads (a licence window, almost always) is ended WINDOW_GRACE later and // listed as needing activation; Try again on it leaves the user the whole LOAD_LIMIT to deal with it. scan::load_in_child_with(&exe, m, LOAD_LIMIT, window_rule(&patient, m), &stop) }; let progress_app = app.clone(); let mut progress = |pr: &scan::Progress| { let p = progress_app.state::<Plugins>(); lock(&p.state).progress = Some(pr.clone()); if pr.done < pr.total { // Up for as long as the module loads: an activation window that opens meanwhile is this plugin's. let text = format!("Looking for plugins: loading {} ({} of {})", pr.module, pr.done + 1, pr.total); crate::bar_call(&progress_app, "notice", json!({ "text": text, "stay": true })); } p.broadcast(json!({ "type": "status", "status": p.status() })); }; // Saved as it goes, and listed: a module with a moduleinfo.json is in the studio's list before anything loads, // and a module that needed activation is remembered even if the app closes half way. let check_app = app.clone(); let mut checkpoint = |c: &scan::Cache| { let p = check_app.state::<Plugins>(); p.save_scan_file(&ScanFile { cache: c.clone(), last: last.clone() }); let had = lock(&p.state).found.len(); p.take_cache(c, None); if lock(&p.state).found.len() != had { p.broadcast(json!({ "type": "status", "status": p.status() })); } }; // A module whose every plugin the user hid isn't loaded when it changes (they may have hidden it for its window). let hidden = { let st = lock(&p.state); scan::Hidden { plugins: st.settings.hidden_plugins.clone(), vendors: st.settings.hidden_vendors.clone() } }; let (mut cache, stats) = scan::scan_saving(&roots, &base, &retry, &hidden, &p.stop_scan, &mut load, &mut progress, &mut checkpoint); restore_stamps(&mut cache, &old); let done = LastScan { millis: stats.millis, at: stats.at, read: stats.read, loaded: stats.loaded }; p.save_scan_file(&ScanFile { cache: cache.clone(), last: Some(done.clone()) }); eprintln!( "[plugins] scanned {} modules ({} read, {} loaded one at a time, {} couldn't be read, {} can't run here{}): {} plugins ({} effects, {} instruments) in {} ms", stats.modules, stats.read, stats.loaded, stats.failed, stats.unsupported, if stats.stopped { ", stopped by the user" } else { "" }, stats.plugins, stats.effects, stats.instruments, stats.millis ); for u in scan::unread(&cache) { eprintln!("[plugins] {UNREAD}: {} ({})", u.path, u.error); } p.take_cache(&cache, Some(&done)); let waiters = { let mut st = lock(&p.state); st.stats = Some(stats.clone()); st.scanning = false; st.progress = None; st.last_check = Some(Instant::now()); std::mem::take(&mut st.scan_waiters) }; for w in waiters { let _ = w.send(true); } p.broadcast(json!({ "type": "status", "status": p.status() })); let (shown, unread, added) = { let st = lock(&p.state); let added = Plugins::visible(&st).iter().filter(|x| !before.contains(&x.plugin.id)).count(); (Plugins::visible(&st).len(), st.unread.len(), added) }; let msg = match (trigger, stats.stopped, unread) { (_, true, _) => format!("Scan stopped: {shown} plugins so far"), (Trigger::Quick, false, _) => { // The quick check speaks only when it found something, and clears the loading notice it put up. let new_unread = unread.saturating_sub(unread_before); match (added, new_unread) { (0, 0) if loads.get() == 0 && !first => return, (0, 0) => String::new(), (a, 0) => count(a, "new plugin", "new plugins"), (0, n) => format!("{} (see Manage plugins)", count(n, "plugin needs activation or didn't load", "plugins need activation or didn't load")), (a, n) => format!("{}; {n} need activation or didn't load (see Manage plugins)", count(a, "new plugin", "new plugins")), } } (_, false, 0) => format!("{shown} plugins found"), (_, false, n) => format!("{shown} plugins found; {n} need activation or didn't load (see Manage plugins)"), }; crate::bar_call(&app, "notice", json!(msg)); });}/// The studio asked for the list: a quick check in the background, at most every QUICK_EVERY. The list it asked for is/// answered at once from what's known; the page hears `status` when the check adds something.fn quick_check_soon(app: &AppHandle) { let p = app.state::<Plugins>(); let due = { let st = lock(&p.state); st.settings.enabled && !st.scanning && st.last_check.is_none_or(|t| t.elapsed() >= QUICK_EVERY) }; if due { lock(&p.state).last_check = Some(Instant::now()); start_scan(app, Mode::Changed, Trigger::Quick); }}/// Stops the scan under way (Stop scanning in the menu, Stop in the plugin manager): the module loading is ended, what/// was read so far is kept, and the rest is left for the next scan.fn stop_scan(app: &AppHandle) { let p = app.state::<Plugins>(); if lock(&p.state).scanning { eprintln!("[plugins] the user stopped the scan"); p.stop_scan.store(true, Ordering::SeqCst); }}/// The page that owned instances is going (a reload, another site): they're closed, its listener and its answer to the/// prompt forgotten.pub fn page_changed(app: &AppHandle, owner: &str) { let p = app.state::<Plugins>(); let gone: Vec<Inst> = { let mut st = lock(&p.state); st.channels.remove(owner); st.declined.remove(owner); *st.pages.entry(owner.to_string()).or_insert(0) += 1; let ids: Vec<u32> = st.instances.iter().filter(|(_, i)| i.owner == owner).map(|(id, _)| *id).collect(); ids.into_iter().filter_map(|id| st.instances.remove(&id)).collect() }; if gone.is_empty() { return; } for i in &gone { if let Some(sid) = i.stream { close_stream(app, sid, ring::STATE_STOPPED); } } let app = app.clone(); std::thread::spawn(move || { let p = app.state::<Plugins>(); for i in gone { if let Some(conn) = p.host.current().filter(|c| c.generation == i.generation) { let _ = close_on_host(&conn, i.host); } } });}/// The app is closing: a scan under way stops (its child is ended) and the host goes.pub fn shutdown(app: &AppHandle) { let p = app.state::<Plugins>(); p.stop_scan.store(true, Ordering::SeqCst); p.host.stop("stopped");}/// The bar's answer to its question.pub fn answer(app: &AppHandle, yes: bool) { let p = app.state::<Plugins>(); let asked = lock(&p.state).asking.as_ref().map(|(a, _)| *a); match (asked, yes) { (Some(Ask::Enable), true) => { // "Turn on and scan" the first time; "Turn on" after (the last scan's list stands). set_enabled(app, true); } (Some(Ask::Scan), true) => { let waiting = lock(&p.state).asking.take().map(|(_, w)| w); crate::bar_call(app, "ask", Value::Null); // Those waiting hear when the scan ends. { let mut st = lock(&p.state); st.scan_waiters.extend(waiting.into_iter().flatten()); } start_scan(app, Mode::Changed, Trigger::User); if !lock(&p.state).scanning { for w in std::mem::take(&mut lock(&p.state).scan_waiters) { let _ = w.send(false); } } } _ => { let waiting = { let mut st = lock(&p.state); st.declined.insert("site".into()); st.asking.take().map(|(_, w)| w) }; for w in waiting.into_iter().flatten() { let _ = w.send(false); } crate::bar_call(app, "ask", Value::Null); } }}/// Asks the user a question in the bar (or adds the caller to those waiting for the one asked); the answer comes/// through `answer`. None when another question is up.fn ask(app: &AppHandle, which: Ask) -> Option<mpsc::Receiver<bool>> { let p = app.state::<Plugins>(); let mut st = lock(&p.state); let (tx, rx) = mpsc::channel(); match &mut st.asking { Some((a, waiting)) if *a == which => { waiting.push(tx); return Some(rx); } Some(_) => return None, None => {} } let never = st.stats.is_none(); st.asking = Some((which, vec![tx])); drop(st); let q = match which { Ask::Enable => json!({ "text": if never { "Let the studio use the plugins installed on this PC? The app will look for them now." } else { "Let the studio use the plugins installed on this PC?" }, "yes": if never { "Turn on and scan" } else { "Turn on" }, "no": "Not now", }), Ask::Scan => json!({ "text": "Look for plugins on this PC now? Plugins that need activation may show their activation window once.", "yes": "Scan", "no": "Not now", }), }; crate::bar_call(app, "ask", q); Some(rx)}// ---- the title bar's menu ----/// Menu text: one line, ampersands kept as themselves (Windows menus take "&" as the accelerator mark).fn menu_text(s: &str) -> String { let s: String = s.chars().filter(|c| !c.is_control()).take(80).collect(); s.replace('&', "&&")}/// The app's menu, kept short: plugins on or off and where they stand, Manage plugins… (the plugin manager, manager.rs:/// the list with favourites and Hide, Try again, the folders with their ticks, every kind of scan), and Scan for/// plugins (Stop scanning while one runs). Debug builds add the plugin test page.pub fn show_menu(app: &AppHandle, x: f64, y: f64) -> tauri::Result<()> { let Some(window) = app.get_window("main") else { return Ok(()) }; let p = app.state::<Plugins>(); let supported = p.host.exe_present(); let (enabled, scanning, progress, shown, unread, scanned) = { let st = lock(&p.state); (st.settings.enabled, st.scanning, st.progress.clone(), Plugins::visible(&st).len(), st.unread.len(), st.stats.is_some()) }; let toggle = CheckMenuItem::with_id(app, "plugins:toggle", "Use my plugins in the studio", supported, enabled, None::<&str>)?; let info = if !supported { "Plugins need the installed app (this copy is the portable one)".to_string() } else if !enabled { "Your installed plugins, in the studio's mixer slots".to_string() } else if let (true, Some(pr)) = (scanning, &progress) { format!("Looking for plugins: {} of {}", (pr.done + 1).min(pr.total.max(1)), pr.total) } else if scanning { "Looking for plugins…".to_string() } else if !scanned { "Not scanned yet: press Scan for plugins".to_string() } else if unread > 0 { format!("{shown} plugins in the studio; {unread} need activation or didn't load") } else { format!("{shown} plugins in the studio") }; let info = MenuItem::with_id(app, "plugins:info", menu_text(&info), false, None::<&str>)?; let manage = MenuItem::with_id(app, "plugins:manage", "Manage plugins…", supported, None::<&str>)?; let scan_item = if scanning { MenuItem::with_id(app, "plugins:stop", "Stop scanning", enabled, None::<&str>)? } else { MenuItem::with_id(app, "plugins:scan", "Scan for plugins", enabled, None::<&str>)? }; let menu = Menu::with_items(app, &[&toggle, &info, &manage, &PredefinedMenuItem::separator(app)?, &scan_item])?; { menu.append(&PredefinedMenuItem::separator(app)?)?; menu.append(&MenuItem::with_id(app, "plugins:test", "Plugin test page (debug build)", true, None::<&str>)?)?; } window.popup_menu_at(&menu, LogicalPosition::new(x, y))}pub fn on_menu(app: &AppHandle, id: &str) { let p = app.state::<Plugins>(); match id { "plugins:toggle" => { let on = !p.enabled(); set_enabled(app, on); } "plugins:manage" => { if let Err(e) = manager::open(app) { eprintln!("[plugins] couldn't open the plugin manager: {e}"); } } "plugins:scan" => start_scan(app, Mode::Changed, Trigger::User), "plugins:stop" => stop_scan(app), "plugins:test" => { if let Err(e) = testpage::open(app) { eprintln!("[plugins] couldn't open the test page: {e}"); } } _ => {} }}/// Adds `item` to the list, or takes it off if it's there (compared without case).fn toggle(list: &mut Vec<String>, item: &str) { if let Some(i) = list.iter().position(|x| x.eq_ignore_ascii_case(item)) { list.remove(i); } else { list.push(item.to_string()); }}/// Changes what the user chose for the studio's list (plugins and vendors hidden, favourites): saved, and the pages and/// the plugin manager hear it (the studio lists again).fn set_choices(app: &AppHandle, f: impl FnOnce(&mut Settings)) { let p = app.state::<Plugins>(); let settings = { let mut st = lock(&p.state); f(&mut st.settings); st.settings.clone() }; p.save_settings(&settings); p.broadcast(json!({ "type": "status", "status": p.status() }));}/// After a folder left the list or lost its tick: plugins found only there leave the lists too, with no scan (nothing/// loads). The cache still remembers them, so ticking the folder again loads nothing that was read or failed before.fn forget_outside(app: &AppHandle) { let p = app.state::<Plugins>(); p.load_found(); p.broadcast(json!({ "type": "status", "status": p.status() }));}/// Ticks a listed folder (it's scanned: a quick check of it now, with plugins on) or unticks it (its plugins leave the/// list, nothing loads).fn tick_folder(app: &AppHandle, path: &str, on: bool) { let p = app.state::<Plugins>(); let settings = { let mut st = lock(&p.state); if !set_ticked(&mut st.settings, path, on) { return; } st.settings.clone() }; p.save_settings(&settings); p.tell_manager(); eprintln!("[plugins] the folder {path} is {}", if on { "ticked" } else { "unticked" }); if on { start_scan(app, Mode::Changed, Trigger::User); } else { forget_outside(app); }}/// Takes a folder the user added off the list (default folders can only be unticked).fn remove_folder(app: &AppHandle, path: &str) { let p = app.state::<Plugins>(); let settings = { let mut st = lock(&p.state); let same = |f: &String| folders::norm(Path::new(f)) == folders::norm(Path::new(path)); st.settings.folders.retain(|f| !same(f)); st.settings.unticked.retain(|f| !same(f)); st.settings.clone() }; p.save_settings(&settings); eprintln!("[plugins] removed the folder {path}"); forget_outside(app);}/// Why a folder can't be added, if it can't: it's already scanned (it or a folder it's in is on the list), or it's/// one that's never looked in.fn cant_add(listed: &[Listed], folder: &Path) -> Option<String> { if scan::never_scanned(folder) { return Some("FL Studio's own plugins and AAX plugins can't be used here".into()); } listed .iter() .find(|l| folders::within(folder, &l.folder.path)) .map(|l| format!("That folder is in the list already ({})", l.folder.path.display()))}/// Adds a folder the user picked (Windows' folder picker in the plugin manager) and scans it, with plugins on. Refused,/// with why, when it's in the list already (or inside a folder that is) or never looked in.fn add_folder(app: &AppHandle, folder: PathBuf) -> Result<(), String> { let p = app.state::<Plugins>(); let path = folder.to_string_lossy().to_string(); if let Some(why) = cant_add(&p.listed(), &folder) { return Err(why); } let settings = { let mut st = lock(&p.state); st.settings.folders.push(path.clone()); st.settings.clone() }; p.save_settings(&settings); p.tell_manager(); eprintln!("[plugins] added the folder {path}"); // Adding a folder is asking for it to be scanned. start_scan(app, Mode::Changed, Trigger::User); Ok(())}/// Windows' own folder picker, owned by `owner` (the plugin manager's window).fn pick_folder(owner: u64) -> Option<PathBuf> { use windows::core::w; use windows::Win32::Foundation::HWND; use windows::Win32::System::Com::{CoCreateInstance, CoInitializeEx, CoTaskMemFree, CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED}; use windows::Win32::UI::Shell::{FileOpenDialog, IFileOpenDialog, FOS_FORCEFILESYSTEM, FOS_PATHMUSTEXIST, FOS_PICKFOLDERS, SIGDN_FILESYSPATH}; // SAFETY: COM on this thread of our own, the dialog's objects used and released here. unsafe { let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED); let dialog: IFileOpenDialog = CoCreateInstance(&FileOpenDialog, None, CLSCTX_INPROC_SERVER).ok()?; let options = dialog.GetOptions().ok()?; dialog.SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST).ok()?; let _ = dialog.SetTitle(w!("Add a plugin folder")); let _ = dialog.SetOkButtonLabel(w!("Add folder")); dialog.Show(Some(HWND(owner as usize as *mut _))).ok()?; let item = dialog.GetResult().ok()?; let name = item.GetDisplayName(SIGDN_FILESYSPATH).ok()?; let path = name.to_string().ok(); CoTaskMemFree(Some(name.0 as *const _)); path.map(PathBuf::from) }}// ---- the page's commands (site.js) ----/// Whether plugins can be used, and are on.pub async fn plugins_status(app: AppHandle, webview: Webview) -> Result<Value, String> { caller(&webview)?; Ok(app.state::<Plugins>().status())}/// Events for this page: status changes, lost instances, latency changes, edits in a plugin's editor.pub async fn plugins_subscribe(app: AppHandle, webview: Webview, events: Channel<Value>) -> Result<(), String> { let owner = caller(&webview)?; lock(&app.state::<Plugins>().state).channels.insert(owner, events); Ok(())}/// Asks the user, in the title bar, to turn plugins on ("Turn on and scan" the first time). True when they're on.pub async fn plugins_request_enable(app: AppHandle, webview: Webview) -> Result<bool, String> { let owner = caller(&webview)?; let p = app.state::<Plugins>(); if !p.host.exe_present() { return Ok(false); } { let st = lock(&p.state); if st.settings.enabled { return Ok(true); } if st.declined.contains(&owner) { return Ok(false); } } let Some(rx) = ask(&app, Ask::Enable) else { return Ok(false) }; blocking(move || Ok(rx.recv_timeout(Duration::from_secs(120)).unwrap_or(false))).await}/// Asks the user, in the title bar, to scan for plugins now. The page can't start a full scan itself, only the user's/// press does (`plugins_list` runs the quick check, which reads only new or changed files). Resolves true when a scan/// the user started has finished (its result is in `plugins_list`).pub async fn plugins_request_scan(app: AppHandle, webview: Webview) -> Result<bool, String> { let owner = caller(&webview)?; let p = app.state::<Plugins>(); let rx = { let mut st = lock(&p.state); if !st.settings.enabled { return Err(OFF.into()); } if st.declined.contains(&owner) { return Ok(false); } if st.scanning { // One is under way: wait for it. let (tx, rx) = mpsc::channel(); st.scan_waiters.push(tx); Some(rx) } else { None } }; let rx = match rx { Some(rx) => rx, None => match ask(&app, Ask::Scan) { Some(rx) => rx, None => return Ok(false), }, }; // The answer, then (for a yes) the scan's end: one module at a time can take a while. blocking(move || Ok(rx.recv_timeout(Duration::from_secs(30 * 60)).unwrap_or(false))).await}/// The plugins found (effects first, instruments marked), less those the user hid, the user's favourites marked/// (`favourite: true`), answered at once. It also starts the quick check in the background (at most every QUICK_EVERY):/// the folders the user ticked are listed and compared with the cache, and only a new or changed module is read (loaded/// one at a time when it has no moduleinfo.json, never one that failed before). The page hears `status` when that adds/// plugins. A page can't name what's read or loaded.pub async fn plugins_list(app: AppHandle, webview: Webview) -> Result<Vec<ListedPlugin>, String> { caller(&webview)?; let p = app.state::<Plugins>(); let list = { let st = lock(&p.state); if !st.settings.enabled { return Err(OFF.into()); } Plugins::visible(&st) }; quick_check_soon(&app); Ok(list)}/// The plugins in the folders that can't run here (old format, 32-bit, ARM), each with why, for the studio to show/// greyed: file names, never folders. Read from the files; none of them is ever loaded.pub async fn plugins_unsupported(app: AppHandle, webview: Webview) -> Result<Vec<scan::Unsupported>, String> { caller(&webview)?; let p = app.state::<Plugins>(); let st = lock(&p.state); if !st.settings.enabled { return Err(OFF.into()); } Ok(st.unsupported.clone())}/// Opens the plugin manager (manager.rs), or brings it forward: the studio's "Manage plugins…". The page learns only/// whether it opened (not in the portable app); nothing in the window reaches the page, and the page can't act in it.pub async fn plugins_manage(app: AppHandle, webview: Webview) -> Result<bool, String> { caller(&webview)?; manager::open(&app).map_err(|e| e.to_string())}/// Opens an instance of plugin `id` at the page's sample rate and block size.pub async fn plugins_open( app: AppHandle, webview: Webview, id: String, sample_rate: f64, block_size: Option<u32>, label: Option<String>, offline: Option<bool>,) -> Result<Value, String> { let owner = caller(&webview)?; let id = id.to_ascii_uppercase(); if !valid_id(&id) { return Err("not a plugin ID".into()); } if !(8000.0..=384000.0).contains(&sample_rate) { return Err("unsupported sample rate".into()); } let block = block_size.unwrap_or(128).clamp(32, 4096); let p = app.state::<Plugins>(); if !p.enabled() { return Err(OFF.into()); } let found = { let st = lock(&p.state); st.found .iter() .find(|f| f.cid == id && !scan::is_hidden(&f.plugin, &st.settings.hidden_plugins, &st.settings.hidden_vendors)) .cloned() .ok_or("no plugin with that ID on this PC")? }; let roots: Vec<String> = p.roots().iter().map(|r| r.to_string_lossy().to_string()).collect(); if !proto::module_allowed(&found.module, &roots) { return Err("that plugin isn't in one of the plugin folders".into()); } if lock(&p.state).instances.values().filter(|i| i.owner == owner).count() >= MAX_INSTANCES { return Err(format!("{MAX_INSTANCES} plugins are open on this page already")); } let owner_hwnd = owner_window(&app); let label = clean_label(&label.unwrap_or_default()); let offline = offline.unwrap_or(false); let page = lock(&p.state).pages.get(&owner).copied().unwrap_or(0); blocking(move || { let p = app.state::<Plugins>(); let conn = p.host.connect(&roots, owner_hwnd)?; let req = Request::Open { module: found.module.clone(), cid: found.cid.clone(), rate: sample_rate, block, offline }; let (v, _) = conn.request(&req, Vec::new(), Duration::from_secs(60))?; let opened: Opened = serde_json::from_value(v).map_err(|e| e.to_string())?; let instance = { let mut st = lock(&p.state); let why = if !st.settings.enabled { Some(OFF) } else if st.pages.get(&owner).copied().unwrap_or(0) != page { // The page that asked has gone (a reload, another page) while the plugin was loading: nobody would // ever close this instance. Some("the page changed while the plugin was opening") } else { None }; if let Some(why) = why { drop(st); let _ = close_on_host(&conn, opened.inst); return Err(why.into()); } let n = st.next; st.next += 1; st.instances.insert( n, Inst { owner, generation: conn.generation, host: opened.inst, id: found.cid.clone(), name: opened.name.clone(), label, rate: sample_rate, block, stream: None, }, ); n }; Ok(json!({ "instance": instance, "plugin": found.plugin, "name": opened.name, "sampleRate": sample_rate, "blockSize": block, "offline": offline, "latency": opened.latency, "tail": opened.tail, "inputs": opened.inputs, "outputs": opened.outputs, "inBuses": opened.in_buses, "outBuses": opened.out_buses, "layout": layout_name(&opened), "hasEditor": opened.has_editor, "params": opened.params, "bypassParam": opened.bypass_param, })) }) .await}pub async fn plugins_close(app: AppHandle, webview: Webview, instance: u32) -> Result<(), String> { let owner = caller(&webview)?; let p = app.state::<Plugins>(); let i = { let mut st = lock(&p.state); match st.instances.get(&instance) { Some(i) if i.owner == owner => st.instances.remove(&instance), _ => None, } } .ok_or("no such instance")?; if let Some(sid) = i.stream { close_stream(&app, sid, ring::STATE_STOPPED); } blocking(move || { let p = app.state::<Plugins>(); if let Some(conn) = p.host.current().filter(|c| c.generation == i.generation) { close_on_host(&conn, i.host).map(|_| ())?; } Ok(()) }) .await}/// Closes an instance in the host. One whose audio thread is stuck in the plugin can't be torn down, and stays stuck/// whatever the page does next: that's a hang, so the host is ended now (its other pages hear `lost`) and starts again.fn close_on_host(conn: &host::Conn, inst: u32) -> Result<Value, String> { let r = conn.request(&Request::Close { inst }, Vec::new(), Duration::from_secs(10)).map(|(v, _)| v); if let Err(e) = &r { if e.contains("stuck") { eprintln!("[plugins] instance {inst} is stuck in its plugin and couldn't close; ending the plugin host"); conn.kill("hung"); } } r}/// Shows the plugin's own editor in its window, titled "<plugin> (<label>)", or hides it.pub async fn plugins_editor(app: AppHandle, webview: Webview, instance: u32, show: bool, label: Option<String>) -> Result<Value, String> { let owner = caller(&webview)?; let p = app.state::<Plugins>(); let (conn, inst) = p.instance(&owner, instance)?; let (title, at) = { let mut st = lock(&p.state); let editors = st.settings.editors.clone(); let i = st.instances.get_mut(&instance).ok_or("no such instance")?; if let Some(l) = label { i.label = clean_label(&l); } let title = if i.label.is_empty() { i.name.clone() } else { format!("{} ({})", i.name, i.label) }; (title, editors.get(&i.id).copied()) }; if show { // The host may bring its window to the front (Windows lets only the foreground app give that away). // SAFETY: a plain Win32 call about a process we started. unsafe { let _ = windows::Win32::UI::WindowsAndMessaging::AllowSetForegroundWindow(conn.pid); } } blocking(move || { let req = Request::Editor { inst, show, title, x: at.map(|a| a[0]), y: at.map(|a| a[1]) }; conn.request(&req, Vec::new(), host::EDITOR_LIMIT).map(|(v, _)| v) }) .await}/// The plugin's state (component and controller) as bytes to keep with the mix.pub async fn plugins_get_state(app: AppHandle, webview: Webview, instance: u32) -> Result<Response, String> { let owner = caller(&webview)?; let (conn, inst) = app.state::<Plugins>().instance(&owner, instance)?; blocking(move || conn.request(&Request::GetState { inst }, Vec::new(), Duration::from_secs(30)).map(|(_, b)| Response::new(b))).await}/// Restores state from `plugins_get_state` (the bytes are the body; the instance is in the Plugin-Instance header).pub async fn plugins_set_state(app: AppHandle, webview: Webview, request: tauri::ipc::Request<'_>) -> Result<(), String> { let owner = caller(&webview)?; let instance = header_u32(&request, "plugin-instance")?; let bytes = body_bytes(request.body())?; let (conn, inst) = app.state::<Plugins>().instance(&owner, instance)?; blocking(move || conn.request(&Request::SetState { inst }, bytes, Duration::from_secs(60)).map(|_| ())).await}pub async fn plugins_params(app: AppHandle, webview: Webview, instance: u32) -> Result<Value, String> { let owner = caller(&webview)?; let (conn, inst) = app.state::<Plugins>().instance(&owner, instance)?; blocking(move || conn.request(&Request::Params { inst }, Vec::new(), Duration::from_secs(30)).map(|(v, _)| v)).await}/// A parameter's normalized value (0 to 1).pub async fn plugins_set_param(app: AppHandle, webview: Webview, instance: u32, id: u32, value: f64) -> Result<(), String> { let owner = caller(&webview)?; let (conn, inst) = app.state::<Plugins>().instance(&owner, instance)?; blocking(move || conn.request(&Request::SetParam { inst, id, value }, Vec::new(), Duration::from_secs(10)).map(|_| ())).await}/// Flushes the plugin (tails, delay lines); answers with its latency.pub async fn plugins_reset(app: AppHandle, webview: Webview, instance: u32) -> Result<Value, String> { let owner = caller(&webview)?; let (conn, inst) = app.state::<Plugins>().instance(&owner, instance)?; blocking(move || conn.request(&Request::Reset { inst }, Vec::new(), Duration::from_secs(20)).map(|(v, _)| v)).await}pub async fn plugins_bypass(app: AppHandle, webview: Webview, instance: u32, on: bool) -> Result<Value, String> { let owner = caller(&webview)?; let (conn, inst) = app.state::<Plugins>().instance(&owner, instance)?; blocking(move || conn.request(&Request::Bypass { inst, on }, Vec::new(), Duration::from_secs(10)).map(|(v, _)| v)).await}/// The audio path for an instance: a ring in a shared buffer, handed to the page (`sharedbufferreceived`, with/// `{kind: "juicewrld-plugins-ring", stream}`) and to the host. `mode` "realtime" plays `latency` frames behind (at/// least 256); "offline" waits for every block (an OfflineAudioContext). A new stream replaces the instance's last.pub async fn plugins_stream(app: AppHandle, webview: Webview, instance: u32, mode: String, latency: Option<u32>) -> Result<Value, String> { let owner = caller(&webview)?; let p = app.state::<Plugins>(); let (conn, inst) = p.instance(&owner, instance)?; let offline = match mode.as_str() { "realtime" => false, "offline" => true, _ => return Err("mode is realtime or offline".into()), }; let (rate, block, old) = { let mut st = lock(&p.state); let i = st.instances.get_mut(&instance).ok_or("no such instance")?; (i.rate, i.block, i.stream.take()) }; if let Some(old) = old { close_stream(&app, old, ring::STATE_STOPPED); let c = conn.clone(); let _ = blocking(move || c.request(&Request::Detach { inst }, Vec::new(), Duration::from_secs(10))).await; } let frames = if offline { 0 } else { latency.unwrap_or(1024).clamp(256, 16384).div_ceil(128) * 128 }; let capacity = ring::capacity_for(frames, block); let layout = ring::Layout { channels: ring::CHANNELS, capacity, latency: frames, mode: offline as u32, rate: rate as u32, max_block: block }; let sid = { let mut st = lock(&p.state); let sid = st.next_stream; st.next_stream += 1; sid }; // Made on the main thread, where WebView2 lives; the handle goes to the host before the page sees anything. let (tx, rx) = tokio_oneshot(); let process = conn.process_handle(); webview .with_webview(move |w| { // SAFETY: on the main thread, inside with_webview. let r = unsafe { shared::create(&w, ring::bytes_for(capacity)) }.map_err(|e| e.to_string()).and_then(|s| { // SAFETY: the buffer is ours and as long as the ring needs. unsafe { ring::Ring::new(s.ptr, s.len) }.init(layout)?; let h = give_handle(process, s.mapping)?; let len = s.len; STREAMS.with(|m| m.borrow_mut().insert(sid, s)); Ok((h, len)) }); let _ = tx.send(r); }) .map_err(|e| e.to_string())?; let (handle, len) = rx.await.map_err(|_| "the window went away".to_string())??; let c = conn.clone(); if let Err(e) = blocking(move || c.request(&Request::Attach { inst, handle, size: len as u64 }, Vec::new(), Duration::from_secs(10))).await { close_stream(&app, sid, ring::STATE_STOPPED); return Err(e); } { let mut st = lock(&p.state); match st.instances.get_mut(&instance) { Some(i) => i.stream = Some(sid), None => { drop(st); close_stream(&app, sid, ring::STATE_STOPPED); return Err("no such instance".into()); } } } let (tx, rx) = tokio_oneshot(); webview .with_webview(move |w| { let r = STREAMS.with(|m| match m.borrow().get(&sid) { // SAFETY: on the main thread, inside with_webview. Some(s) => unsafe { shared::post(&w, s, &json!({ "kind": "juicewrld-plugins-ring", "version": ring::VERSION, "stream": sid, "instance": instance })) } .map_err(|e| e.to_string()), None => Err("the stream closed".to_string()), }); let _ = tx.send(r); }) .map_err(|e| e.to_string())?; rx.await.map_err(|_| "the window went away".to_string())??; Ok(json!({ "stream": sid, "mode": mode, "latency": frames, "capacity": capacity, "sampleRate": rate, "blockSize": block }))}/// Ends the instance's stream (the page's node is going away).pub async fn plugins_stream_close(app: AppHandle, webview: Webview, instance: u32) -> Result<(), String> { let owner = caller(&webview)?; let p = app.state::<Plugins>(); let (conn, inst) = p.instance(&owner, instance)?; let old = lock(&p.state).instances.get_mut(&instance).and_then(|i| i.stream.take()); if let Some(sid) = old { close_stream(&app, sid, ring::STATE_STOPPED); } blocking(move || conn.request(&Request::Detach { inst }, Vec::new(), Duration::from_secs(10)).map(|_| ())).await}/// Offline, request and response: planar stereo f32 in (left then right, `Plugin-Frames` frames each, the body), the/// processed audio out the same way. For an instance without a stream.pub async fn plugins_render(app: AppHandle, webview: Webview, request: tauri::ipc::Request<'_>) -> Result<Response, String> { let owner = caller(&webview)?; let instance = header_u32(&request, "plugin-instance")?; let frames = header_u32(&request, "plugin-frames")?; let bytes = body_bytes(request.body())?; if bytes.len() != frames as usize * 8 { return Err("the audio isn't the stereo length it says".into()); } let (conn, inst) = app.state::<Plugins>().instance(&owner, instance)?; let limit = Duration::from_secs(30) + Duration::from_millis(frames as u64 / 10); blocking(move || conn.request(&Request::Render { inst, frames }, bytes, limit).map(|(_, b)| Response::new(b))).await}/// Measuring the IPC itself (debug builds' test page only, never granted to the site): the bytes back as sent.pub async fn plugins_bench_echo(webview: Webview, request: tauri::ipc::Request<'_>) -> Result<Response, String> { if !cfg!(debug_assertions) || webview.label() != TEST_LABEL { return Err("not here".into()); } Ok(Response::new(body_bytes(request.body())?))}/// Measuring a Channel (debug builds' test page only): `count` messages of `bytes` bytes, `every` ms apart.pub async fn plugins_bench_channel(webview: Webview, to: Channel<Response>, bytes: u32, count: u32, every: u32) -> Result<(), String> { if !cfg!(debug_assertions) || webview.label() != TEST_LABEL { return Err("not here".into()); } std::thread::spawn(move || { for n in 0..count { let mut b = vec![0u8; bytes.max(8) as usize]; b[..4].copy_from_slice(&n.to_le_bytes()); if to.send(Response::new(b)).is_err() { break; } std::thread::sleep(Duration::from_millis(every as u64)); } }); Ok(())}/// The menu's and the plugin manager's actions, by name, for the debug build's test page (never granted to the site): a/// scripted run can do what the user does there. "toggle" (plugins on or off), "scan", "stop", "try-again" (a module's/// file name), "hide" (a plugin ID), "hide-vendor" (a vendor's name), "tick" (a listed folder's path), "add-folder" (a/// path, as the folder picker would give it), "remove-folder" (a path), "manage" (opens the plugin manager), and "menu"/// to list what the app knows.pub async fn plugins_test_action(app: AppHandle, webview: Webview, action: String, arg: Option<String>) -> Result<Value, String> { if !cfg!(debug_assertions) || webview.label() != TEST_LABEL { return Err("not here".into()); } let p = app.state::<Plugins>(); let arg = arg.unwrap_or_default(); match action.as_str() { "toggle" => on_menu(&app, "plugins:toggle"), "scan" => on_menu(&app, "plugins:scan"), "tick" => { let on = p.listed().iter().any(|l| folders::norm(&l.folder.path) == folders::norm(Path::new(&arg)) && l.on); tick_folder(&app, &arg, !on); } "add-folder" => add_folder(&app, PathBuf::from(&arg))?, "remove-folder" => remove_folder(&app, &arg), "stop" => on_menu(&app, "plugins:stop"), "try-again" => { let path = lock(&p.state).unread.iter().find(|u| u.name.eq_ignore_ascii_case(&arg)).map(|u| u.path.clone()); let path = path.ok_or("no such module needs trying again")?; start_scan(&app, Mode::TryAgain(path), Trigger::User); } "hide" => set_choices(&app, |s| toggle(&mut s.hidden_plugins, &arg)), "hide-vendor" => set_choices(&app, |s| toggle(&mut s.hidden_vendors, &arg)), "manage" => { manager::open(&app).map_err(|e| e.to_string())?; } "menu" => {} _ => return Err("unknown action".into()), } let listed = p.listed(); let st = lock(&p.state); Ok(json!({ "enabled": st.settings.enabled, "folders": listed.iter().map(|l| json!({ "path": l.folder.path, "kind": l.folder.kind.label(), "from": l.folder.from, "on": l.on, "added": l.added, "exists": l.exists })).collect::<Vec<_>>(), "unread": st.unread.iter().map(|u| json!({ "name": u.name, "problem": u.problem, "error": u.error })).collect::<Vec<_>>(), "unsupported": st.unsupported.iter().map(|u| json!({ "file": u.file, "reason": u.reason, "why": u.why, "replacement": u.replacement })).collect::<Vec<_>>(), "found": st.found.iter().map(|f| json!({ "id": f.cid, "name": f.plugin.name, "vendor": f.plugin.vendor, "kind": f.plugin.kind, "copies": f.others.len() + 1, "hidden": scan::is_hidden(&f.plugin, &st.settings.hidden_plugins, &st.settings.hidden_vendors) })).collect::<Vec<_>>(), "hiddenPlugins": st.settings.hidden_plugins, "hiddenVendors": st.settings.hidden_vendors, "favourites": st.settings.favourites, "scanning": st.scanning, "stats": st.stats, }))}/// A one-shot channel that works across the main thread and the async runtime.fn tokio_oneshot<T>() -> (OneshotTx<T>, OneshotRx<T>) { let (tx, rx) = mpsc::channel(); (OneshotTx(tx), OneshotRx(rx))}struct OneshotTx<T>(mpsc::Sender<T>);impl<T> OneshotTx<T> { fn send(self, v: T) -> Result<(), ()> { self.0.send(v).map_err(|_| ()) }}struct OneshotRx<T>(mpsc::Receiver<T>);impl<T: Send + 'static> std::future::IntoFuture for OneshotRx<T> { type Output = Result<T, ()>; type IntoFuture = std::pin::Pin<Box<dyn std::future::Future<Output = Result<T, ()>> + Send>>; fn into_future(self) -> Self::IntoFuture { Box::pin(async move { tauri::async_runtime::spawn_blocking(move || self.0.recv_timeout(Duration::from_secs(10)).map_err(|_| ())) .await .unwrap_or(Err(())) }) }}mod tests { use super::*; fn url(s: &str) -> Url { Url::parse(s).unwrap() } fn only_the_site_and_the_debug_test_page_may_use_plugins() { for ok in ["https://juicewrld.io/", "https://juicewrld.io/studio/abc?x=1"] { assert!(allowed_caller("site", &url(ok), false), "{ok}"); } for (label, page) in [ ("site", "http://juicewrld.io/"), ("site", "https://www.juicewrld.io/"), ("site", "https://juicewrld.io.evil.com/"), ("site", "https://juicewrld.io:8443/"), ("site", "https://discord.com/login"), ("site", "about:blank"), ("bar", "https://juicewrld.io/"), ("bar", "http://tauri.localhost/index.html"), ("other", "https://juicewrld.io/"), ] { assert!(!allowed_caller(label, &url(page), true), "{label} {page}"); } // The test page, in debug builds only, and only as itself. assert!(allowed_caller(TEST_LABEL, &url("http://jwtest.localhost/index.html"), true)); assert!(!allowed_caller(TEST_LABEL, &url("http://jwtest.localhost/index.html"), false)); assert!(!allowed_caller(TEST_LABEL, &url("https://juicewrld.io/"), true)); assert!(!allowed_caller("site", &url("http://jwtest.localhost/index.html"), true)); } fn plugin_ids_are_class_ids_never_paths() { assert!(valid_id("ED57BD725C60467EA64DD2F400758B6F")); assert!(valid_id("ed57bd725c60467ea64dd2f400758b6f")); for bad in [ "", "ED57BD725C60467EA64DD2F400758B6", "ED57BD725C60467EA64DD2F400758B6FF", r"D:\Plugins\Example.vst3", "../../../../windows/system32/evil", "ED57BD725C60467EA64DD2F400758B6G", ] { assert!(!valid_id(bad), "{bad}"); } } fn labels_are_one_short_line() { assert_eq!(clean_label(" Insert 3 "), "Insert 3"); assert_eq!(clean_label("Insert\n3\u{0007}"), "Insert3"); assert_eq!(clean_label(&"x".repeat(200)).len(), 60); } fn raw_bodies_come_as_bytes_or_as_numbers() { assert_eq!(body_bytes(&InvokeBody::Raw(vec![1, 2, 255])).unwrap(), [1, 2, 255]); assert_eq!(body_bytes(&InvokeBody::Json(json!([1, 2, 255]))).unwrap(), [1, 2, 255]); assert!(body_bytes(&InvokeBody::Json(json!([1, 256]))).is_err()); assert!(body_bytes(&InvokeBody::Json(json!({"a": 1}))).is_err()); } fn settings_read_what_older_files_have() { let s: Settings = serde_json::from_str("{}").unwrap(); assert_eq!(s, Settings::default()); assert!(!s.enabled, "off until the user turns it on"); let s: Settings = serde_json::from_str(r#"{"enabled":true,"folders":["D:\\VST"],"editors":{"AB":[10,-20]},"later":1}"#).unwrap(); assert!(s.enabled && s.folders == ["D:\\VST"] && s.editors["AB"] == [10, -20]); assert!(s.hidden_plugins.is_empty() && s.hidden_vendors.is_empty()); let s: Settings = serde_json::from_str(r#"{"hiddenPlugins":["AB"],"hiddenVendors":["Example Audio"]}"#).unwrap(); assert_eq!(s.hidden_plugins, ["AB"]); assert_eq!(s.hidden_vendors, ["Example Audio"]); assert!(s.unticked.is_empty(), "every folder ticked to start with"); let s: Settings = serde_json::from_str(r#"{"unticked":["D:\\VST"]}"#).unwrap(); assert_eq!(s.unticked, [r"D:\VST"]); assert!(s.favourites.is_empty(), "no favourites in a file from before them"); let s: Settings = serde_json::from_str(r#"{"favourites":["AB"]}"#).unwrap(); assert_eq!(s.favourites, ["AB"]); } /// A folder of the test's own, under JW_TEST_DIR when set, else the system's temp folder. fn tmp(name: &str) -> PathBuf { let base = std::env::var_os("JW_TEST_DIR").map(PathBuf::from).unwrap_or_else(std::env::temp_dir); let d = base.join(format!("jw-app-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d } /// What the plugin manager sets is kept in plugins.json and read back as it was: favourites, folder ticks (a folder /// unticked stays listed, unscanned; ticked again, it's scanned), hidden plugins, a folder added. fn favourites_and_ticks_are_saved() { let dir = tmp("settings"); assert_eq!(read_settings(&dir), Settings::default(), "no file: plugins off, nothing chosen"); let defaults = vec![folders::Folder { path: dir.join("VST3"), kind: folders::Kind::Test, from: "test" }]; std::fs::create_dir_all(dir.join("VST3")).unwrap(); std::fs::create_dir_all(dir.join("Mine")).unwrap(); let mut s = Settings { enabled: true, folders: vec![dir.join("Mine").to_string_lossy().to_string()], ..Default::default() }; let id = "ED57BD725C60467EA64DD2F400758B6F"; assert!(set_in(&mut s.favourites, id, true)); assert!(!set_in(&mut s.favourites, &id.to_lowercase(), true), "a favourite once, whatever its case"); assert!(set_ticked(&mut s, &dir.join("VST3").to_string_lossy(), false)); assert!(!set_ticked(&mut s, &dir.join("vst3").to_string_lossy().to_uppercase(), false), "unticked already, however it's spelt"); assert!(set_in(&mut s.hidden_plugins, "AB", true)); write_settings(&dir, &s); let back = read_settings(&dir); assert_eq!(back, s); assert_eq!(back.favourites, [id]); assert!(!dir.join("plugins.json.tmp").exists(), "written through a temporary file, renamed into place"); let list = folder_list(&defaults, &back); assert_eq!(list.iter().map(|l| (l.on, l.added)).collect::<Vec<_>>(), [(false, false), (true, true)]); assert_eq!(ticked(&list), [dir.join("Mine")], "the unticked folder is listed, not scanned"); // Ticked again and the star taken off: saved too. let mut s = back; assert!(set_ticked(&mut s, &dir.join("VST3").to_string_lossy(), true)); assert!(set_in(&mut s.favourites, id, false)); write_settings(&dir, &s); let back = read_settings(&dir); assert!(back.unticked.is_empty() && back.favourites.is_empty()); assert_eq!(ticked(&folder_list(&defaults, &back)).len(), 2); let _ = std::fs::remove_dir_all(&dir); } /// A made-up module for the scan tests: a single .vst3 file (loaded through the test's own loader, which loads /// nothing) or a bundle with a moduleinfo.json. fn fake_module(dir: &Path, name: &str, with_info: bool) { if with_info { let b = dir.join(format!("{name}.vst3")); std::fs::create_dir_all(b.join("Contents").join("x86_64-win")).unwrap(); std::fs::write(b.join("Contents").join("x86_64-win").join(format!("{name}.vst3")), b"MZ fake").unwrap(); std::fs::create_dir_all(b.join("Contents").join("Resources")).unwrap(); let info = format!( r#"{{"Name":"{name}","Factory Info":{{"Vendor":"Example"}},"Classes":[{{"CID":"ABCDEF01ABCDEF01ABCDEF01ABCDEF01","Category":"Audio Module Class","Name":"{name}","Vendor":"Example","Version":"1","Sub Categories":["Fx"]}}]}}"# ); std::fs::write(scan::moduleinfo_path(&b), info).unwrap(); } else { std::fs::write(dir.join(format!("{name}.vst3")), format!("MZ {name}")).unwrap(); } } /// Rescan everything reads again every module that read fine, and nothing that failed; Retry failed loads every /// failure again with the window rule standing, Try again one without it; a rescan stopped half way keeps every /// plugin it hadn't read again, with its own stamp. Only made-up modules, through a loader that loads nothing. fn rescan_everything_and_retry_failed_read_what_they_say() { let d = tmp("modes"); fake_module(&d, "Info", true); fake_module(&d, "One", false); fake_module(&d, "Two", false); fake_module(&d, "Locked", false); let roots = vec![d.clone()]; let loaded = std::cell::RefCell::new(Vec::<String>::new()); let mut load = |m: &Path| -> scan::Loaded { let name = m.file_stem().unwrap().to_string_lossy().to_string(); loaded.borrow_mut().push(name.clone()); if name == "Locked" { return Err(scan::LoadError { problem: scan::Problem::Window, message: "a licence window".into() }); } let n = if name == "One" { 1 } else { 2 }; Ok(("Example".into(), vec![scan::Class { cid: format!("1234567890ABCDEF000000000000000{n}"), category: "Audio Module Class".into(), name, sub_categories: vec!["Fx".into()], ..Default::default() }])) }; let names = |c: &scan::Cache| scan::plugins(c).into_iter().map(|f| f.plugin.name).collect::<Vec<_>>(); let go = AtomicBool::new(false); let (first, _) = scan::scan(&roots, &scan::Cache::default(), &HashSet::new(), &go, &mut load, &mut |_| {}); assert_eq!(*loaded.borrow(), ["Locked", "One", "Two"], "the bundle read from its moduleinfo.json"); assert_eq!(names(&first), ["Info", "One", "Two"]); assert_eq!(scan::unread(&first).len(), 1); // Scan (new and changed): nothing. loaded.borrow_mut().clear(); let (again, _) = scan::scan(&roots, &first, &HashSet::new(), &go, &mut load, &mut |_| {}); assert!(loaded.borrow().is_empty()); assert_eq!(again, first); // Rescan everything: every module that read fine, the failure left alone; the stamps are the files' own after. loaded.borrow_mut().clear(); let (retry, patient) = retry_sets(&Mode::Everything, &first, &roots); assert!(retry.is_empty() && patient.is_empty()); let (mut all, stats) = scan::scan(&roots, &for_rescan(&first), &retry, &go, &mut load, &mut |_| {}); restore_stamps(&mut all, &first); assert_eq!(*loaded.borrow(), ["One", "Two"]); assert_eq!(stats.read, 3, "the bundle again from its moduleinfo.json, the two loaded"); assert_eq!(names(&all), ["Info", "One", "Two"]); assert_eq!(scan::unread(&all).len(), 1, "the failure remembered, not loaded"); assert!(all.modules.values().all(|m| m.stamp != RESCAN)); assert_eq!(all, first, "the same files, read again: the same cache"); // Stopped half way: what it hadn't read again keeps its entry and its own stamp. loaded.borrow_mut().clear(); let stop = AtomicBool::new(false); let mut stop_after_one = |m: &Path| -> scan::Loaded { stop.store(true, Ordering::SeqCst); load(m) }; let (mut half, stats) = scan::scan(&roots, &for_rescan(&first), &HashSet::new(), &stop, &mut stop_after_one, &mut |_| {}); restore_stamps(&mut half, &first); assert!(stats.stopped); assert_eq!(loaded.borrow().len(), 1); assert_eq!(names(&half), ["Info", "One", "Two"], "nothing lost"); assert_eq!(half, first, "the module it didn't get to has its own stamp back: the next quick check loads nothing"); loaded.borrow_mut().clear(); let (next, _) = scan::scan(&roots, &half, &HashSet::new(), &go, &mut load, &mut |_| {}); assert!(loaded.borrow().is_empty() && next == first); // Retry failed: the failure loads again (the window rule standing), nothing else. loaded.borrow_mut().clear(); let (retry, patient) = retry_sets(&Mode::Failed, &first, &roots); assert_eq!(retry.len(), 1); assert!(patient.is_empty(), "the window rule stands for every one"); let locked = d.join("Locked.vst3"); assert_eq!(window_rule(&patient, &locked), Some(WINDOW_GRACE)); let _ = scan::scan(&roots, &first, &retry, &go, &mut load, &mut |_| {}); assert_eq!(*loaded.borrow(), ["Locked"]); // Try again on it: the same module, without the window rule (the user is there for its window). let key = scan::unread(&first)[0].path.clone(); let (retry, patient) = retry_sets(&Mode::TryAgain(key.clone()), &first, &roots); assert!(retry.contains(&key)); assert_eq!(window_rule(&patient, &locked), None); assert_eq!(window_rule(&patient, &d.join("One.vst3")), Some(WINDOW_GRACE)); // A folder unticked since: its failures aren't retried. assert!(retry_sets(&Mode::Failed, &first, &[d.join("elsewhere")]).0.is_empty()); let _ = std::fs::remove_dir_all(&d); } /// The folder list: the defaults, then the user's own (a copy of a default isn't listed twice), each with its tick /// (compared without case); a folder the user added that has gone is listed but not scanned. fn the_folder_list_has_ticks_kinds_and_the_users_own() { let d = |p: &str, kind| folders::Folder { path: PathBuf::from(p), kind, from: "test" }; let defaults = vec![d(r"X:\PF\Common Files\VST3", folders::Kind::Vst3), d(r"X:\PF\VSTPlugins", folders::Kind::Vst2)]; let s = Settings { folders: vec![r"x:\pf\vstplugins".into(), r"Y:\Gone for good".into()], unticked: vec![r"X:\PF\VSTPLUGINS\".into()], ..Default::default() }; let l = folder_list(&defaults, &s); let got: Vec<_> = l.iter().map(|l| (l.folder.kind.label(), l.on, l.added, l.exists)).collect(); assert_eq!(got, [("VST 3", true, false, true), ("VST 2", false, false, true), ("Added", true, true, false)]); assert_eq!(ticked(&l), [PathBuf::from(r"X:\PF\Common Files\VST3")]); // Adding: not a folder already scanned (or inside one), not one that's never looked in. assert!(cant_add(&l, Path::new(r"X:\PF\Common Files\VST3\Vendor")).is_some()); assert!(cant_add(&l, Path::new(r"x:\pf\common files\vst3")).is_some()); assert!(cant_add(&l, Path::new(r"X:\FL Studio 2025\Plugins\Fruity\Effects")).is_some()); assert!(cant_add(&l, Path::new(r"X:\Program Files\Common Files\Avid\Audio\Plug-Ins")).is_some()); assert!(cant_add(&l, Path::new(r"Z:\Other")).is_none()); assert!(cant_add(&l, Path::new(r"X:\PF")).is_none(), "a folder holding listed ones may be added"); } fn hiding_toggles_without_case_and_menu_text_is_one_line() { let mut list = vec!["Example Audio".to_string()]; toggle(&mut list, "example audio"); assert!(list.is_empty()); toggle(&mut list, "Other"); assert_eq!(list, ["Other"]); assert_eq!(menu_text("Tom & Jerry\nFX"), "Tom && JerryFX"); } /// Debug builds read JW_PLUGINS_FOLDERS; a release build never does (it has no such override). fn the_folder_override_is_a_debug_builds_alone() { if cfg!(debug_assertions) { let f = folders_override(); assert_eq!(f.is_some(), std::env::var_os("JW_PLUGINS_FOLDERS").is_some()); } else { assert!(folders_override().is_none()); } } /// The capabilities as shipped: the site gets presence, the bar's room, notifications, the like shortcut's three /// and the plugin commands, nothing of Tauri's own or the title bar's, on https://juicewrld.io alone; the bar gets /// none of the plugin commands. fn the_site_may_call_exactly_these_commands() { let site: Value = serde_json::from_str(include_str!("../../capabilities/site.json")).unwrap(); assert_eq!(site["remote"]["urls"], json!(["https://juicewrld.io/*"])); assert_eq!(site["webviews"], json!(["site"])); assert_eq!(site["local"], json!(false)); let mut granted: Vec<&str> = site["permissions"].as_array().unwrap().iter().map(|p| p.as_str().unwrap()).collect(); granted.sort(); let mut want = vec!["allow-presence", "allow-site-under-bar", "allow-notify", "allow-like-shortcut-get", "allow-like-shortcut-set", "allow-like-notice"]; want.extend(SITE_COMMANDS.iter().map(|c| PERMISSIONS[*c])); want.sort(); assert_eq!(granted, want); assert!(!granted.iter().any(|p| p.contains(':')), "no plugin's or Tauri's own permissions"); assert!(!granted.iter().any(|p| p.contains("bench") || p.contains("test")), "the IPC measurements and test actions are the debug test page's alone"); let bar: Value = serde_json::from_str(include_str!("../../capabilities/bar.json")).unwrap(); assert!(!bar["permissions"].as_array().unwrap().iter().any(|p| p.as_str().unwrap().contains("plugins"))); assert!(!bar["permissions"].as_array().unwrap().iter().any(|p| p.as_str().unwrap().contains("manager"))); } /// The plugin manager's capability, as shipped: its own commands and nothing else (none of the site's, none of /// Tauri's own), for its own webview on the app's bundled page (local, no remote address); the site's capability /// grants none of them, so the site's window can't use them (and each checks its caller again: manager::allowed). fn the_managers_capability_is_its_own() { let m: Value = serde_json::from_str(include_str!("../../capabilities/plugin-manager.json")).unwrap(); assert_eq!(m["identifier"], json!("plugin-manager")); assert_eq!(m["webviews"], json!([manager::LABEL])); assert_eq!(m["local"], json!(true)); assert!(m.get("remote").is_none(), "no web page gets it"); assert!(m.get("windows").is_none(), "its webview alone, by label"); let mut granted: Vec<&str> = m["permissions"].as_array().unwrap().iter().map(|p| p.as_str().unwrap()).collect(); granted.sort(); let mut want: Vec<String> = MANAGER_COMMANDS.iter().map(|c| format!("allow-{}", c.replace('_', "-"))).collect(); want.sort(); assert_eq!(granted, want); assert!(!granted.iter().any(|p| p.contains(':')), "nothing of Tauri's own"); assert!(!granted.iter().any(|p| p.starts_with("allow-plugins-") || *p == "allow-presence"), "none of the site's"); let site: Value = serde_json::from_str(include_str!("../../capabilities/site.json")).unwrap(); let site_perms = site["permissions"].as_array().unwrap(); assert!(!site_perms.iter().any(|p| p.as_str().unwrap().contains("manager")), "the site can't call the manager's commands"); // The site may open it, and that's all (plugins_manage answers whether it opened). assert!(site_perms.contains(&json!("allow-plugins-manage"))); // The app ships the capability: tauri.conf.json lists it beside the bar's and the site's. let conf: Value = serde_json::from_str(include_str!("../../tauri.conf.json")).unwrap(); assert_eq!(conf["app"]["security"]["capabilities"], json!(["bar", "site", "plugin-manager"])); } /// The commands the plugin manager's capability grants, by name (manager.rs). const MANAGER_COMMANDS: &[&str] = &[ "manager_state", "manager_subscribe", "manager_enable", "manager_scan", "manager_stop", "manager_retry", "manager_favourite", "manager_hide", "manager_folder", "manager_add_folder", "manager_remove_folder", ]; /// The commands the site's capability grants, by name. const SITE_COMMANDS: &[&str] = &[ "plugins_status", "plugins_subscribe", "plugins_request_enable", "plugins_request_scan", "plugins_list", "plugins_unsupported", "plugins_manage", "plugins_open", "plugins_close", "plugins_editor", "plugins_get_state", "plugins_set_state", "plugins_params", "plugins_set_param", "plugins_reset", "plugins_bypass", "plugins_stream", "plugins_stream_close", "plugins_render", ]; static PERMISSIONS: std::sync::LazyLock<HashMap<&'static str, &'static str>> = std::sync::LazyLock::new(|| { SITE_COMMANDS.iter().map(|c| (*c, Box::leak(format!("allow-{}", c.replace('_', "-")).into_boxed_str()) as &str)).collect() }); fn every_command_is_declared_to_tauri() { // build.rs declares the app's commands; one missing there has no permission and nobody could call it. let build = include_str!("../../build.rs"); for c in SITE_COMMANDS.iter().chain(["plugins_bench_echo", "plugins_bench_channel", "plugins_test_action"].iter()) { assert!(build.contains(&format!("\"{c}\"")), "{c} isn't in build.rs"); } let main = include_str!("../main.rs"); for c in SITE_COMMANDS { assert!(main.contains(&format!("plugins::{c}")), "{c} isn't in the invoke handler"); } // The site's commands outside the plugins: declared, and handled. for (c, handled) in [("site_under_bar", "site_under_bar,"), ("notify", "notices::notify,"), ("like_notice", "like_shortcut::like_notice,")] { assert!(build.contains(&format!("\"{c}\"")), "{c} isn't in build.rs"); assert!(main.contains(handled), "{c} isn't in the invoke handler"); } for c in MANAGER_COMMANDS { assert!(build.contains(&format!("\"{c}\"")), "{c} isn't in build.rs"); assert!(main.contains(&format!("plugins::manager::{c}")), "{c} isn't in the invoke handler"); } // The debug test page may open the manager too (as the site may), and use none of its commands. let test = include_str!("testpage.rs"); assert!(test.contains("\"allow-plugins-manage\"")); assert!(!test.contains("allow-manager")); }}