juicewrld-desktopsrc-taurisrcpluginsmanager.rs
1.4.2Released Nov 21, 2026
manager.rs
496 lines22.0 KBRust//! The plugin manager: a window of the app's own (ui/plugins.html, plugins.js, plugins.css), like FL Studio's Plugin//! Manager. A table of everything in the plugin folders (the plugins found, the modules that need activation or didn't//! load, and the plugins that can't run here, greyed), sortable, with a Find box and a count; a star per plugin (the//! studio's add-effect menu lists favourites first), Hide or Show (a hidden plugin never reaches the studio), Try again//! for a module that failed; the plugin search paths with their ticks, Add folder… (Windows' own picker) and Remove for//! the user's own; Scan (new and changed), Rescan everything, Retry failed and Stop, with the scan's progress live; and//! the switch, Use my plugins in the studio.//!//! It opens from the title bar's menu (Manage plugins…) and when the site asks (`plugins_manage`, the page API's//! `manage()`), which only opens it: nothing in it reaches the page. Its commands are its own: capabilities///! plugin-manager.json grants them to this one webview on the app's bundled page, and each checks its caller again//! (`allowed`), so the site can't call them and the manager can't call the site's. Everything done here is the user's//! own click, so the manager may name folders and modules, which the site never can; each one it names is checked//! against the lists the app made (a listed folder, a module that failed), and a folder is only ever added through//! Windows' folder picker.use super::{ blocking, folder_list, folders, lock, pick_folder, scan, set_choices, set_in, start_scan, stop_scan, valid_id, Mode, Plugins, Settings, Trigger, TRADEMARK,};use serde_json::{json, Value};use std::path::Path;use std::sync::mpsc;use tauri::ipc::Channel;use tauri::{AppHandle, Manager, Theme, Url, Webview, WebviewUrl, WebviewWindowBuilder, WindowEvent};/// The manager's window and webview.pub const LABEL: &str = "plugin-manager";/// Its page, in the app's bundled UI (ui/).const PAGE: &str = "plugins.html";/// One of the app's own bundled pages: http://tauri.localhost on Windows (tauri://localhost elsewhere).fn app_page(url: &Url) -> bool { match url.scheme() { "http" | "https" => url.host_str() == Some("tauri.localhost") && url.port().is_none(), "tauri" => url.host_str() == Some("localhost"), _ => false, }}/// Who may use the manager's commands: its own window on its own page, and nothing else (not the site, not the title/// bar, not the debug test page, not a web page).pub fn allowed(label: &str, url: &Url) -> bool { label == LABEL && app_page(url) && url.path() == format!("/{PAGE}")}fn caller(webview: &Webview) -> Result<(), String> { let url = webview.url().map_err(|_| "no page".to_string())?; if allowed(webview.label(), &url) { Ok(()) } else { Err("only the plugin manager may do that".into()) }}/// Opens the manager, or brings it forward. False when this copy of the app can't run plugins (the portable app). A/// quiet test run (JW_NO_FOCUS, debug builds) opens it without taking focus, behind the other windows.pub fn open(app: &AppHandle) -> tauri::Result<bool> { if !super::supported() { return Ok(false); } let quiet = crate::test_switch("JW_NO_FOCUS"); if let Some(w) = app.get_webview_window(LABEL) { if !quiet { let _ = w.unminimize(); let _ = w.set_focus(); } return Ok(true); } let mut builder = WebviewWindowBuilder::new(app, LABEL, WebviewUrl::App(PAGE.into())) .title("Plugin manager") .inner_size(1200.0, 740.0) .min_inner_size(900.0, 520.0) // An owned window has no taskbar button of its own: minimized, it would shrink to a stray title bar, so it // goes with the app's window instead (and closes when the user is done with it). .minimizable(false) .center() .theme(Some(Theme::Dark)) .background_color(crate::BG) // The same options as the app's other webviews, which share its WebView2 profile. .additional_browser_args(crate::BROWSER_ARGS) .disable_drag_drop_handler() .focused(!quiet) // Its own page and nothing else: no link or script takes this window to a web page. .on_navigation(|url| app_page(url) || url.as_str() == "about:blank"); // Owned by the app's window, as FL Studio's plugin manager is by FL Studio's: above it, minimized and closed with it. if let Some(owner) = app.get_window("main").and_then(|w| w.hwnd().ok()) { builder = builder.owner_raw(owner); } let window = builder.build()?; if quiet { if let Ok(h) = window.hwnd() { crate::to_back(h.0 as isize); } } let close_app = app.clone(); window.on_window_event(move |e| { if let WindowEvent::Destroyed = e { lock(&close_app.state::<Plugins>().state).manager = None; } }); eprintln!("[plugins] the plugin manager opened"); Ok(true)}/// What Hide or Show is about.pub enum Target<'a> { Plugin(&'a str), Vendor(&'a str),}/// Hides or shows, as the manager asks. A plugin: hidden by its ID; shown, it's in the studio's list again even when its/// whole vendor was hidden (the vendor's other plugins stay hidden, each by its ID from then on). A vendor: every plugin/// of it, those installed later too; shown again, every one of them, those hidden one by one included.pub fn hide(s: &mut Settings, found: &[scan::Found], target: Target, on: bool) { match target { Target::Plugin(id) => { set_in(&mut s.hidden_plugins, id, on); let vendor = found.iter().find(|f| f.cid.eq_ignore_ascii_case(id)).map(|f| f.plugin.vendor.clone()); if let Some(v) = vendor.filter(|v| !on && s.hidden_vendors.iter().any(|h| h.eq_ignore_ascii_case(v))) { set_in(&mut s.hidden_vendors, &v, false); for f in found.iter().filter(|f| f.plugin.vendor.eq_ignore_ascii_case(&v) && !f.cid.eq_ignore_ascii_case(id)) { set_in(&mut s.hidden_plugins, &f.cid, true); } } } Target::Vendor(v) => { set_in(&mut s.hidden_vendors, v, on); if !on { for f in found.iter().filter(|f| f.plugin.vendor.eq_ignore_ascii_case(v)) { set_in(&mut s.hidden_plugins, &f.cid, false); } } } }}/// Why a module couldn't be read, in words (the Status column's hover).pub fn why(u: &scan::Unread) -> String { match u.problem { scan::Problem::Timeout => "It didn't answer in time: it may be waiting for activation. Try again gives you time to deal with it.".to_string(), scan::Problem::Crashed => "It crashed as it loaded.".to_string(), scan::Problem::Failed => format!("It didn't load: {}", u.error), scan::Problem::Window => "It opened a window as it loaded: it may need activation. Try again gives you time to deal with it.".to_string(), }}/// Everything the manager shows. `fresh` looks for the default folders again (when the window opens: a DAW installed/// since adds its own); otherwise the ones last found.fn state(app: &AppHandle, fresh: bool) -> Value { let p = app.state::<Plugins>(); let supported = p.host.exe_present(); let defaults = match (supported, fresh) { (false, _) => Vec::new(), (true, true) => p.rediscover(), (true, false) => p.defaults(), }; let st = lock(&p.state); let s = &st.settings; let has = |list: &[String], x: &str| list.iter().any(|v| v.eq_ignore_ascii_case(x)); let plugins: Vec<Value> = st .found .iter() .map(|f| { let hidden = if has(&s.hidden_plugins, &f.cid) { json!("plugin") } else if has(&s.hidden_vendors, &f.plugin.vendor) { json!("vendor") } else { Value::Null }; json!({ "id": f.cid, "name": f.plugin.name, "vendor": f.plugin.vendor, "version": f.plugin.version, "kind": f.plugin.kind, "categories": f.plugin.categories, "surround": f.plugin.surround, "file": f.plugin.module, "path": f.module, // Other copies of it (an older version, the same plugin installed twice): never opened for it. "copies": f.others, "favourite": has(&s.favourites, &f.cid), "hidden": hidden, }) }) .collect(); let failed: Vec<Value> = st .unread .iter() .map(|u| { let name = Path::new(&u.name).file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| u.name.clone()); let activation = matches!(u.problem, scan::Problem::Timeout | scan::Problem::Window); json!({ "path": u.path, "file": u.name, "name": name, "problem": u.problem, "activation": activation, "why": why(u) }) }) .collect(); let unsupported: Vec<Value> = st .unsupported .iter() .map(|u| json!({ "path": u.path, "file": u.file, "name": u.name, "format": u.format, "arch": u.arch, "reason": u.reason, "replacement": u.replacement, "why": u.why })) .collect(); let folders: Vec<Value> = folder_list(&defaults, s) .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(); json!({ "supported": supported, "enabled": s.enabled, "scanned": st.stats.is_some(), "scanning": st.scanning, "progress": st.progress, "scan": st.stats, "plugins": plugins, "failed": failed, "unsupported": unsupported, "folders": folders, "trademark": TRADEMARK, })}/// Scans and folder changes wait while a scan runs (it was started with the folders as they were).fn idle(p: &Plugins) -> Result<(), String> { if lock(&p.state).scanning { Err("A scan is under way: stop it, or wait for it to end".into()) } else { Ok(()) }}/// Scans need plugins on (turning them on is the user's own choice, in this window's switch or the menu).fn turned_on(p: &Plugins) -> Result<(), String> { if !p.host.exe_present() { Err("Plugins need the installed app".into()) } else if !p.enabled() { Err("Turn on Use my plugins in the studio first".into()) } else { Ok(()) }}/// The manager's view: plugins, failures, the greyed ones, the folders, the scan. `fresh` looks for the default folders/// again.pub async fn manager_state(app: AppHandle, webview: Webview, fresh: Option<bool>) -> Result<Value, String> { caller(&webview)?; Ok(state(&app, fresh.unwrap_or(false)))}/// The manager's events: every change (the scan's progress, the lists, what the user chose); it reads its state again.pub async fn manager_subscribe(app: AppHandle, webview: Webview, events: Channel<Value>) -> Result<(), String> { caller(&webview)?; lock(&app.state::<Plugins>().state).manager = Some(events); Ok(())}/// The switch: Use my plugins in the studio. Turning it on starts the first scan (or a quick check, after the first).pub async fn manager_enable(app: AppHandle, webview: Webview, on: bool) -> Result<bool, String> { caller(&webview)?; let p = app.state::<Plugins>(); if !p.host.exe_present() { return Err("Plugins need the installed app".into()); } super::set_enabled(&app, on); Ok(p.enabled())}/// Scan: "changed" (new and changed, as Scan for plugins), "everything" (every module that read fine, read again),/// "failed" (every module that failed, loaded again, the window rule standing).pub async fn manager_scan(app: AppHandle, webview: Webview, what: String) -> Result<(), String> { caller(&webview)?; let p = app.state::<Plugins>(); turned_on(&p)?; idle(&p)?; let mode = match what.as_str() { "changed" => Mode::Changed, "everything" => Mode::Everything, "failed" => Mode::Failed, _ => return Err("scan changed, everything or failed".into()), }; start_scan(&app, mode, Trigger::User); Ok(())}/// Stops the scan under way (what was read so far is kept).pub async fn manager_stop(app: AppHandle, webview: Webview) -> Result<(), String> { caller(&webview)?; stop_scan(&app); Ok(())}/// Try again on one module that failed (as its row names it): it loads with the whole time limit and no window rule,/// so the user can deal with its activation window. Only a module the app lists as failed.pub async fn manager_retry(app: AppHandle, webview: Webview, module: String) -> Result<(), String> { caller(&webview)?; let p = app.state::<Plugins>(); turned_on(&p)?; idle(&p)?; let path = lock(&p.state).unread.iter().find(|u| scan::same_path(&u.path) == scan::same_path(&module)).map(|u| u.path.clone()); let path = path.ok_or("That module isn't one that failed")?; eprintln!("[plugins] Try again: {path}"); start_scan(&app, Mode::TryAgain(path), Trigger::User); Ok(())}/// Stars a plugin (the studio's add-effect menu lists favourites first), or takes the star off.pub async fn manager_favourite(app: AppHandle, webview: Webview, id: String, on: bool) -> Result<(), String> { caller(&webview)?; if !valid_id(&id) { return Err("not a plugin ID".into()); } let id = id.to_ascii_uppercase(); set_choices(&app, |s| { set_in(&mut s.favourites, &id, on); }); Ok(())}/// Hides a plugin (`id`) or every plugin of a vendor (`vendor`) from the studio, or shows them again (`hide`).pub async fn manager_hide(app: AppHandle, webview: Webview, id: Option<String>, vendor: Option<String>, on: bool) -> Result<(), String> { caller(&webview)?; let found = lock(&app.state::<Plugins>().state).found.clone(); match (id, vendor) { (Some(id), None) if valid_id(&id) => { let id = id.to_ascii_uppercase(); set_choices(&app, |s| hide(s, &found, Target::Plugin(&id), on)); } (None, Some(v)) if !v.trim().is_empty() => set_choices(&app, |s| hide(s, &found, Target::Vendor(&v), on)), _ => return Err("a plugin ID or a vendor".into()), } Ok(())}/// Ticks a listed folder (scanned, with plugins on) or unticks it (its plugins leave the list; nothing loads). Only a/// folder the list has.pub async fn manager_folder(app: AppHandle, webview: Webview, path: String, on: bool) -> Result<(), String> { caller(&webview)?; let p = app.state::<Plugins>(); idle(&p)?; let listed = p.listed().into_iter().find(|l| folders::norm(&l.folder.path) == folders::norm(Path::new(&path))); let listed = listed.ok_or("That folder isn't in the list")?; super::tick_folder(&app, &listed.folder.path.to_string_lossy(), on); Ok(())}/// Add folder…: Windows' own folder picker, owned by the manager's window. True when a folder was added (and is being/// scanned, with plugins on), false when the picker was cancelled; refused, with why, for a folder in the list already/// (or inside one that is) or one that's never looked in.pub async fn manager_add_folder(app: AppHandle, webview: Webview) -> Result<bool, String> { caller(&webview)?; idle(&app.state::<Plugins>())?; let owner = webview.window().hwnd().map(|h| h.0 as usize as u64).unwrap_or(0); // The picker runs COM on a thread of its own, as long as the user takes. let (tx, rx) = mpsc::channel(); std::thread::spawn(move || { let _ = tx.send(pick_folder(owner)); }); let picked = blocking(move || rx.recv().map_err(|_| "the folder picker closed".to_string())).await?; let Some(folder) = picked else { return Ok(false) }; idle(&app.state::<Plugins>())?; super::add_folder(&app, folder)?; Ok(true)}/// Remove: takes a folder the user added off the list (the others can only be unticked).pub async fn manager_remove_folder(app: AppHandle, webview: Webview, path: String) -> Result<(), String> { caller(&webview)?; let p = app.state::<Plugins>(); idle(&p)?; let listed = p.listed().into_iter().find(|l| l.added && folders::norm(&l.folder.path) == folders::norm(Path::new(&path))); let listed = listed.ok_or("Only a folder you added can be removed")?; super::remove_folder(&app, &listed.folder.path.to_string_lossy()); Ok(())}mod tests { use super::*; fn url(s: &str) -> Url { Url::parse(s).unwrap() } fn found(id: &str, name: &str, vendor: &str) -> scan::Found { scan::Found { plugin: scan::Plugin { id: id.into(), name: name.into(), vendor: vendor.into(), version: "1.0".into(), kind: "effect".into(), categories: vec!["Fx".into()], surround: false, module: format!("{name}.vst3"), sdk_version: "VST 3.7".into(), }, module: format!(r"X:\VST3\{name}.vst3"), cid: id.into(), others: Vec::new(), } } /// The manager's commands answer its own window on its own page, and nobody else: not the site's webview (on its /// own address or any other), not the title bar, not the debug test page, not a web page in the manager's window. fn only_the_managers_own_page_may_use_its_commands() { assert!(allowed(LABEL, &url("http://tauri.localhost/plugins.html"))); assert!(allowed(LABEL, &url("https://tauri.localhost/plugins.html"))); assert!(allowed(LABEL, &url("tauri://localhost/plugins.html"))); for (label, page) in [ ("site", "https://juicewrld.io/"), ("site", "https://juicewrld.io/plugins.html"), ("site", "http://tauri.localhost/plugins.html"), ("bar", "http://tauri.localhost/index.html"), ("bar", "http://tauri.localhost/plugins.html"), (super::super::TEST_LABEL, "http://jwtest.localhost/index.html"), (LABEL, "https://juicewrld.io/plugins.html"), (LABEL, "http://tauri.localhost/index.html"), (LABEL, "http://tauri.localhost:8080/plugins.html"), (LABEL, "http://tauri.localhost.evil.com/plugins.html"), (LABEL, "http://jwtest.localhost/plugins.html"), (LABEL, "about:blank"), (LABEL, "data:text/html,<p>plugins</p>"), ] { assert!(!allowed(label, &url(page)), "{label} {page}"); } // And the other way round: the manager's window can't call the site's plugin commands. assert!(!super::super::allowed_caller(LABEL, &url("http://tauri.localhost/plugins.html"), true)); assert!(!super::super::allowed_caller(LABEL, &url("https://juicewrld.io/"), true)); } /// Hidden plugins never reach the studio's list; a vendor hidden takes every plugin of it, and one of them shown /// again comes back alone; favourites are marked, hidden or not. fn hidden_plugins_stay_out_of_the_studios_list() { let a = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; let b = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; let c = "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"; let list = vec![found(a, "Alpha", "Example Audio"), found(b, "Beta", "Example Audio"), found(c, "Gamma", "Other")]; let ids = |s: &Settings| super::super::visible_list(&list, s).into_iter().map(|p| p.plugin.id).collect::<Vec<_>>(); let mut s = Settings::default(); assert_eq!(ids(&s), [a, b, c]); hide(&mut s, &list, Target::Plugin(b), true); assert_eq!(ids(&s), [a, c]); assert_eq!(s.hidden_plugins, [b]); hide(&mut s, &list, Target::Vendor("example audio"), true); assert_eq!(ids(&s), [c], "the whole vendor, compared without case"); // One of a hidden vendor's plugins shown: it alone comes back; the vendor's others stay hidden, by their IDs. hide(&mut s, &list, Target::Plugin(a), false); assert_eq!(ids(&s), [a, c]); assert!(s.hidden_vendors.is_empty()); assert_eq!(s.hidden_plugins, [b]); // The vendor shown again: every one of its plugins, those hidden one by one too. hide(&mut s, &list, Target::Vendor("Example Audio"), true); hide(&mut s, &list, Target::Vendor("Example Audio"), false); assert_eq!(ids(&s), [a, b, c]); assert!(s.hidden_plugins.is_empty() && s.hidden_vendors.is_empty()); // Favourites: marked in the list (and only said when true), kept while hidden. set_in(&mut s.favourites, c, true); set_in(&mut s.favourites, b, true); hide(&mut s, &list, Target::Plugin(b), true); let listed = super::super::visible_list(&list, &s); assert_eq!(listed.iter().map(|p| (p.plugin.id.as_str(), p.favourite)).collect::<Vec<_>>(), [(a, false), (c, true)]); let json = serde_json::to_value(&listed).unwrap(); assert_eq!(json[0].get("favourite"), None, "not a favourite: nothing said"); assert_eq!(json[1]["favourite"], json!(true)); assert_eq!(json[1]["id"], json!(c), "the plugin's own fields as before"); assert_eq!(json[1]["module"], json!("Gamma.vst3"), "its file name, never a folder"); assert!(!json.to_string().contains(r"X:\\VST3"), "no folder reaches the page"); } fn why_a_module_failed_reads_as_a_sentence() { let u = |problem, error: &str| scan::Unread { path: r"X:\VST3\A.vst3".into(), name: "A.vst3".into(), problem, error: error.into() }; assert!(why(&u(scan::Problem::Window, "")).contains("activation")); assert!(why(&u(scan::Problem::Timeout, "")).contains("in time")); assert!(why(&u(scan::Problem::Crashed, "")).contains("crashed")); assert_eq!(why(&u(scan::Problem::Failed, "no factory")), "It didn't load: no factory"); }}