Skip to content

XP event5x XPListening, games, ratings, comments and chat earn five times the XP

leftLeaderboard

juicewrld-desktopsrc-taurisrcpluginsfolders.rs

1.4.2Released Nov 21, 2026

folders.rs

678 lines31.8 KBRust
//! Where to look for plugins: the folders a PC's plugins are installed in, found the way installers and DAWs find them,//! through the environment, Windows' known folders and the registry, never a hard-coded drive. Listed for the user like//! FL Studio's plugin search paths (a tick, the path, the kind); every one that exists is ticked to start with.//!//! - VST 3's own places: Common Files\VST3 (for everyone) and %LOCALAPPDATA%\Programs\Common\VST3 (one user).//! - Where VST 3 bundles also end up, beside the old format's plugins: Common Files\VST2 and Common Files\Steinberg\VST2,//!   Program Files\VSTPlugins, Steinberg\VstPlugins, Native Instruments\VSTPlugins 64 bit, Cakewalk\VstPlugins, and the//!   folder installers record as VSTPluginsPath under SOFTWARE\VST (machine and user). A `.dll` there is an old-format//!   plugin: listed, greyed, never loaded (scan.rs).//! - FL Studio's: every version's Program Files\Image-Line\FL Studio *\Plugins\VST, the folders in FL Studio's own plugin//!   search paths (Software\Image-Line\Shared\Plugin search paths, the ones ticked there, the user's own included), its//!   recorded VST folder, and the folders of the plugins in its plugin database (Documents\Image-Line\FL Studio\Presets\//!   Plugin database\Installed, whose .nfo entries name each plugin's file). Its Fruity plugins are FL Studio's own//!   format and run only inside it: their folders are never listed. Nothing FL Studio owns is ever written.//! - Never Avid's AAX folder (Common Files\Avid): another format altogether.//!//! Everything here reads: the registry (read-only), folder listings and FL Studio's text files. Nothing is loaded.use serde::Serialize;use std::path::{Path, PathBuf};use std::sync::Mutex;/// What a folder is for, shown beside it.#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)]#[serde(rename_all = "camelCase")]pub enum Kind {    /// One of VST 3's own two folders.    Vst3,    /// A folder for old-format plugins, where VST 3 bundles are often installed too.    Vst2,    /// FL Studio's: its plugin folder, its search paths, the folders of the plugins it found.    FlStudio,    /// One the user added.    Added,    /// A debug test run's own (JW_PLUGINS_FOLDERS).    Test,}impl Kind {    /// The kind as the list shows it. (VST is a registered trademark of Steinberg Media Technologies GmbH; the menu    /// says so under the list.)    pub fn label(self) -> &'static str {        match self {            Kind::Vst3 => "VST 3",            Kind::Vst2 => "VST 2",            Kind::FlStudio => "FL Studio",            Kind::Added => "Added",            Kind::Test => "Test run",        }    }}#[derive(Clone, Debug, PartialEq)]pub struct Folder {    pub path: PathBuf,    pub kind: Kind,    /// Where it came from, in words (for the log and the dry run).    pub from: &'static str,}#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum Hive {    /// HKEY_LOCAL_MACHINE    Machine,    /// HKEY_CURRENT_USER    User,}/// Windows' known folders this needs.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum Known {    /// FOLDERID_ProgramFilesX64: C:\Program Files on most PCs.    ProgramFiles,    /// FOLDERID_ProgramFilesCommonX64: Program Files\Common Files.    ProgramFilesCommon,    /// FOLDERID_UserProgramFilesCommon: %LOCALAPPDATA%\Programs\Common.    UserProgramFilesCommon,    /// FOLDERID_Documents (FL Studio keeps its plugin database there).    Documents,}/// What discovery reads from the PC: the environment, known folders and the registry (read-only). The tests fake it.pub trait System {    fn var(&self, name: &str) -> Option<String>;    fn known(&self, folder: Known) -> Option<PathBuf>;    /// A REG_SZ or REG_EXPAND_SZ value, unexpanded.    fn reg_string(&self, hive: Hive, key: &str, value: &str) -> Option<String>;    fn reg_dword(&self, hive: Hive, key: &str, value: &str) -> Option<u32>;    /// The names of a key's subkeys.    fn reg_subkeys(&self, hive: Hive, key: &str) -> Vec<String>;}/// FL Studio's own list of plugin folders, one subkey per folder (path, plugclass, selected, custom).const FL_SEARCH_PATHS: &str = r"Software\Image-Line\Shared\Plugin search paths\List";/// plugclass for FL Studio's own Fruity effects and generators.const FL_FRUITY_CLASSES: [u32; 2] = [2, 3];/// How deep FL Studio's plugin database is looked into (Installed\Effects\VST3\<entry>.nfo).const FL_DB_DEPTH: usize = 3;fn push(out: &mut Vec<Folder>, path: Option<PathBuf>, kind: Kind, from: &'static str) {    if let Some(path) = path {        out.push(Folder { path, kind, from });    }}/// `%NAME%` replaced by the variable's value (`%FLPath%` by FL Studio's install folder); unknown names stay as they are,/// so a path naming one won't exist and is left out.pub fn expand(s: &str, sys: &dyn System, fl_path: Option<&Path>) -> String {    let mut out = String::new();    let mut rest = s;    while let Some(start) = rest.find('%') {        let Some(len) = rest[start + 1..].find('%') else { break };        let name = &rest[start + 1..start + 1 + len];        let value = if name.eq_ignore_ascii_case("FLPath") {            fl_path.map(|p| p.to_string_lossy().to_string())        } else if name.is_empty() {            None        } else {            sys.var(name)        };        out.push_str(&rest[..start]);        match value {            Some(v) => out.push_str(&v),            None => out.push_str(&rest[start..start + len + 2]),        }        rest = &rest[start + len + 2..];    }    out.push_str(rest);    out}/// A path as it's compared: backslashes, no trailing separator, lower case.pub fn norm(p: &Path) -> String {    p.to_string_lossy().replace('/', "\\").trim_end_matches('\\').to_lowercase()}/// Whether `inner` is `outer` or inside it.pub fn within(inner: &Path, outer: &Path) -> bool {    let (i, o) = (norm(inner), norm(outer));    !o.is_empty() && (i == o || (i.len() > o.len() && i.starts_with(&o) && i.as_bytes()[o.len()] == b'\\'))}/// Folders never looked in: FL Studio's own Fruity plugins (they run only inside FL Studio) and Avid's AAX plugins.pub use super::scan::never_scanned;/// FL Studio's install folder (what its paths call %FLPath%).fn fl_install(sys: &dyn System) -> Option<PathBuf> {    for hive in [Hive::User, Hive::Machine] {        if let Some(p) = sys.reg_string(hive, r"Software\Image-Line\Shared\Paths", "Install path") {            return Some(PathBuf::from(expand(&p, sys, None)));        }        if let Some(exe) = sys.reg_string(hive, r"Software\Image-Line\Shared\Paths", "FL Studio") {            if let Some(dir) = Path::new(&expand(&exe, sys, None)).parent() {                return Some(dir.to_path_buf());            }        }    }    None}/// The folders named in FL Studio's plugin database: each .nfo entry's `ps_file_filename_N=` lines name a plugin's/// file, and the folder holding it counts. Read as text, only the lines needed; the Fruity part is skipped. Kept in/// memory and read again only when one of the database's folders changes (a scan in FL Studio adds or removes entries).fn fl_database(documents: &Path, sys: &dyn System, fl_path: Option<&Path>) -> Vec<PathBuf> {    static MEMO: Mutex<Option<(Vec<(PathBuf, u64)>, Vec<String>)>> = Mutex::new(None);    let root = documents.join("Image-Line").join("FL Studio").join("Presets").join("Plugin database").join("Installed");    // The folders and their modification times: a file added or removed in a folder changes its time.    let mut dirs = Vec::new();    let mut stack = vec![(root.clone(), 0usize)];    while let Some((d, depth)) = stack.pop() {        let Ok(meta) = std::fs::metadata(&d) else { continue };        dirs.push((d.clone(), modified_ms(&meta)));        if depth >= FL_DB_DEPTH {            continue;        }        if let Ok(entries) = std::fs::read_dir(&d) {            for e in entries.flatten() {                let name = e.file_name().to_string_lossy().to_lowercase();                if e.file_type().is_ok_and(|t| t.is_dir() && !t.is_symlink()) && name != "fruity" {                    stack.push((e.path(), depth + 1));                }            }        }    }    dirs.sort();    let lines = {        let mut memo = MEMO.lock().unwrap_or_else(|e| e.into_inner());        match memo.as_ref() {            Some((stamps, lines)) if *stamps == dirs => lines.clone(),            _ => {                let mut lines = Vec::new();                for (d, _) in &dirs {                    let Ok(entries) = std::fs::read_dir(d) else { continue };                    for e in entries.flatten() {                        let p = e.path();                        if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("nfo")) {                            continue;                        }                        let Ok(bytes) = std::fs::read(&p) else { continue };                        for line in String::from_utf8_lossy(&bytes).lines() {                            if let Some((key, value)) = line.split_once('=') {                                if key.starts_with("ps_file_filename_") && !value.trim().is_empty() {                                    lines.push(value.trim().to_string());                                }                            }                        }                    }                }                lines.sort();                lines.dedup();                *memo = Some((dirs, lines.clone()));                lines            }        }    };    let mut out: Vec<PathBuf> = Vec::new();    for file in lines {        let file = PathBuf::from(expand(&file, sys, fl_path));        let Some(dir) = file.parent() else { continue };        if !out.iter().any(|o| norm(o) == norm(dir)) {            out.push(dir.to_path_buf());        }    }    out}fn modified_ms(m: &std::fs::Metadata) -> u64 {    m.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_millis() as u64)}/// FL Studio's folders: every version's Plugins\VST, its own search paths (not the Fruity ones; only those ticked/// there), its recorded VST folder, and the folders its plugin database names.fn fl_studio(sys: &dyn System, program_files: Option<&Path>, out: &mut Vec<Folder>) {    let fl_path = fl_install(sys);    if let Some(pf) = program_files {        // "FL Studio 20", "FL Studio 21", "FL Studio 2024", "FL Studio 2025", plain "FL Studio": a version, not its        // other folders ("FL Studio ASIO" is a driver).        let version = |name: &str| {            let n = name.to_lowercase();            n.strip_prefix("fl studio").is_some_and(|rest| rest.is_empty() || rest.trim_start().starts_with(|c: char| c.is_ascii_digit()))        };        let mut versions: Vec<PathBuf> = std::fs::read_dir(pf.join("Image-Line"))            .map(|r| r.flatten().filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && version(&e.file_name().to_string_lossy())).map(|e| e.path()).collect())            .unwrap_or_default();        versions.sort();        for v in versions {            push(out, Some(v.join("Plugins").join("VST")), Kind::FlStudio, "FL Studio's plugin folder");        }    }    let mut keys = sys.reg_subkeys(Hive::User, FL_SEARCH_PATHS);    keys.sort_by_key(|k| k.parse::<u32>().unwrap_or(u32::MAX));    for k in keys {        let key = format!(r"{FL_SEARCH_PATHS}\{k}");        let Some(path) = sys.reg_string(Hive::User, &key, "path") else { continue };        let class = sys.reg_dword(Hive::User, &key, "plugclass").unwrap_or(0);        let selected = sys.reg_dword(Hive::User, &key, "selected").unwrap_or(1) != 0;        if FL_FRUITY_CLASSES.contains(&class) || !selected {            continue;        }        let from = if sys.reg_dword(Hive::User, &key, "custom").unwrap_or(0) != 0 { "added in FL Studio's plugin manager" } else { "FL Studio's plugin search paths" };        push(out, Some(PathBuf::from(expand(&path, sys, fl_path.as_deref()))), Kind::FlStudio, from);    }    push(out, sys.reg_string(Hive::Machine, r"SOFTWARE\Image-Line\Shared\Paths", "VST plugins").map(|p| PathBuf::from(expand(&p, sys, fl_path.as_deref()))), Kind::FlStudio, "FL Studio's VST folder");    push(out, sys.reg_string(Hive::User, r"Software\Image-Line\Shared\Plugins\FL Studio", "VstDir64").map(|p| PathBuf::from(expand(&p, sys, fl_path.as_deref()))), Kind::FlStudio, "FL Studio's VST folder");    if let Some(docs) = sys.known(Known::Documents) {        for dir in fl_database(&docs, sys, fl_path.as_deref()) {            push(out, Some(dir), Kind::FlStudio, "FL Studio's plugin database");        }    }}/// Every default folder, in the order listed, before tidying (`tidy`).pub fn candidates(sys: &dyn System) -> Vec<Folder> {    let var_path = |names: &[&str]| names.iter().find_map(|n| sys.var(n)).filter(|v| !v.trim().is_empty()).map(PathBuf::from);    let common = sys.known(Known::ProgramFilesCommon).or_else(|| var_path(&["CommonProgramW6432", "CommonProgramFiles"]));    let program_files = sys.known(Known::ProgramFiles).or_else(|| var_path(&["ProgramW6432", "ProgramFiles"]));    let user_common = sys        .known(Known::UserProgramFilesCommon)        .or_else(|| var_path(&["LOCALAPPDATA"]).map(|l| l.join("Programs").join("Common")));    let mut out = Vec::new();    push(&mut out, common.as_ref().map(|c| c.join("VST3")), Kind::Vst3, "VST 3's folder for everyone");    push(&mut out, user_common.as_ref().map(|c| c.join("VST3")), Kind::Vst3, "VST 3's folder for one user");    push(&mut out, common.as_ref().map(|c| c.join("VST2")), Kind::Vst2, "the shared VST 2 folder");    push(&mut out, common.as_ref().map(|c| c.join("Steinberg").join("VST2")), Kind::Vst2, "Steinberg's shared VST 2 folder");    if let Some(pf) = &program_files {        push(&mut out, Some(pf.join("VSTPlugins")), Kind::Vst2, "the usual VST 2 folder");        push(&mut out, Some(pf.join("Steinberg").join("VstPlugins")), Kind::Vst2, "Steinberg's VST 2 folder");        push(&mut out, Some(pf.join("Native Instruments").join("VSTPlugins 64 bit")), Kind::Vst2, "Native Instruments' VST 2 folder");        push(&mut out, Some(pf.join("Cakewalk").join("VstPlugins")), Kind::Vst2, "Cakewalk's VST 2 folder");    }    for (hive, from) in [(Hive::Machine, "VSTPluginsPath for everyone"), (Hive::User, "VSTPluginsPath for this user")] {        push(&mut out, sys.reg_string(hive, r"SOFTWARE\VST", "VSTPluginsPath").map(|p| PathBuf::from(expand(&p, sys, None))), Kind::Vst2, from);    }    fl_studio(sys, program_files.as_deref(), &mut out);    out}/// The list as shown: folders that exist, each once (the first kind it came as), none inside another one listed (the/// walk goes into subfolders anyway), none of the folders that are never looked in.pub fn tidy(folders: Vec<Folder>, exists: &dyn Fn(&Path) -> bool) -> Vec<Folder> {    let mut out: Vec<Folder> = Vec::new();    for mut f in folders {        let s = f.path.to_string_lossy().trim_end_matches(['\\', '/']).to_string();        if s.is_empty() || never_scanned(Path::new(&s)) {            continue;        }        // A drive's root keeps its separator (D:\).        f.path = PathBuf::from(if s.ends_with(':') { format!("{s}\\") } else { s });        if !f.path.is_absolute() || !exists(&f.path) || out.iter().any(|o| norm(&o.path) == norm(&f.path)) {            continue;        }        out.push(f);    }    let all = out.clone();    out.retain(|f| !all.iter().any(|o| norm(&o.path) != norm(&f.path) && within(&f.path, &o.path)));    out}/// The default folders on this PC that exist.pub fn defaults(sys: &dyn System) -> Vec<Folder> {    tidy(candidates(sys), &|p| p.is_dir())}/// This PC, as discovery reads it.pub struct Windows;#[cfg(windows)]mod win {    use super::{Hive, Known};    use std::path::PathBuf;    use windows::core::{HSTRING, PWSTR};    use windows::Win32::Foundation::ERROR_SUCCESS;    use windows::Win32::System::Com::CoTaskMemFree;    use windows::Win32::System::Registry::{        RegCloseKey, RegEnumKeyExW, RegGetValueW, RegOpenKeyExW, HKEY, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, REG_DWORD, REG_EXPAND_SZ, REG_SZ, REG_VALUE_TYPE, RRF_NOEXPAND,        RRF_RT_ANY,    };    use windows::Win32::UI::Shell::{        SHGetKnownFolderPath, FOLDERID_Documents, FOLDERID_ProgramFilesCommonX64, FOLDERID_ProgramFilesX64, FOLDERID_UserProgramFilesCommon, KF_FLAG_DONT_VERIFY,    };    fn root(h: Hive) -> HKEY {        match h {            Hive::Machine => HKEY_LOCAL_MACHINE,            Hive::User => HKEY_CURRENT_USER,        }    }    pub fn known(k: Known) -> Option<PathBuf> {        let id = match k {            Known::ProgramFiles => FOLDERID_ProgramFilesX64,            Known::ProgramFilesCommon => FOLDERID_ProgramFilesCommonX64,            Known::UserProgramFilesCommon => FOLDERID_UserProgramFilesCommon,            Known::Documents => FOLDERID_Documents,        };        // SAFETY: the shell allocates the string; it's copied and freed here.        unsafe {            let p: PWSTR = SHGetKnownFolderPath(&id, KF_FLAG_DONT_VERIFY, None).ok()?;            let s = p.to_string().ok();            CoTaskMemFree(Some(p.0 as *const _));            s.filter(|s| !s.is_empty()).map(PathBuf::from)        }    }    /// A value's raw bytes and type, read without expanding anything.    fn value(h: Hive, key: &str, name: &str) -> Option<(REG_VALUE_TYPE, Vec<u8>)> {        let (k, n) = (HSTRING::from(key), HSTRING::from(name));        let mut kind = REG_VALUE_TYPE::default();        let mut size = 0u32;        // SAFETY: reads into buffers of the size the first call reports; read-only access.        unsafe {            if RegGetValueW(root(h), &k, &n, RRF_RT_ANY | RRF_NOEXPAND, Some(&mut kind), None, Some(&mut size)) != ERROR_SUCCESS || size > 1 << 16 {                return None;            }            let mut buf = vec![0u8; size as usize + 2];            let mut size = buf.len() as u32;            if RegGetValueW(root(h), &k, &n, RRF_RT_ANY | RRF_NOEXPAND, Some(&mut kind), Some(buf.as_mut_ptr() as *mut _), Some(&mut size)) != ERROR_SUCCESS {                return None;            }            buf.truncate(size as usize);            Some((kind, buf))        }    }    pub fn reg_string(h: Hive, key: &str, name: &str) -> Option<String> {        let (kind, bytes) = value(h, key, name)?;        if kind != REG_SZ && kind != REG_EXPAND_SZ {            return None;        }        let wide: Vec<u16> = bytes.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).take_while(|&c| c != 0).collect();        Some(String::from_utf16_lossy(&wide)).filter(|s| !s.trim().is_empty())    }    pub fn reg_dword(h: Hive, key: &str, name: &str) -> Option<u32> {        match value(h, key, name)? {            (kind, b) if kind == REG_DWORD && b.len() >= 4 => Some(u32::from_le_bytes([b[0], b[1], b[2], b[3]])),            _ => None,        }    }    pub fn reg_subkeys(h: Hive, key: &str) -> Vec<String> {        let mut out = Vec::new();        let mut hk = HKEY::default();        // SAFETY: a key opened read-only, enumerated and closed here.        unsafe {            if RegOpenKeyExW(root(h), &HSTRING::from(key), None, KEY_READ, &mut hk) != ERROR_SUCCESS {                return out;            }            for i in 0..1024u32 {                let mut name = [0u16; 256];                let mut len = name.len() as u32;                if RegEnumKeyExW(hk, i, Some(PWSTR(name.as_mut_ptr())), &mut len, None, None, None, None) != ERROR_SUCCESS {                    break;                }                out.push(String::from_utf16_lossy(&name[..len as usize]));            }            let _ = RegCloseKey(hk);        }        out    }}impl System for Windows {    fn var(&self, name: &str) -> Option<String> {        std::env::var(name).ok()    }    fn known(&self, folder: Known) -> Option<PathBuf> {        #[cfg(windows)]        return win::known(folder);        #[cfg(not(windows))]        None    }    fn reg_string(&self, hive: Hive, key: &str, value: &str) -> Option<String> {        #[cfg(windows)]        return win::reg_string(hive, key, value);        #[cfg(not(windows))]        None    }    fn reg_dword(&self, hive: Hive, key: &str, value: &str) -> Option<u32> {        #[cfg(windows)]        return win::reg_dword(hive, key, value);        #[cfg(not(windows))]        None    }    fn reg_subkeys(&self, hive: Hive, key: &str) -> Vec<String> {        #[cfg(windows)]        return win::reg_subkeys(hive, key);        #[cfg(not(windows))]        Vec::new()    }}#[cfg(test)]pub mod tests {    use super::*;    use std::collections::HashMap;    /// A PC made up for the tests: its variables, known folders and registry, all pointing into a scratch folder.    #[derive(Default)]    pub struct Fake {        pub vars: HashMap<String, String>,        pub known: HashMap<&'static str, PathBuf>,        /// (hive, key lower-cased, value name) to a string or a number.        pub strings: HashMap<(bool, String, String), String>,        pub dwords: HashMap<(bool, String, String), u32>,    }    impl Fake {        pub fn string(&mut self, hive: Hive, key: &str, name: &str, v: &str) {            self.strings.insert((hive == Hive::Machine, key.to_lowercase(), name.to_string()), v.to_string());        }        pub fn dword(&mut self, hive: Hive, key: &str, name: &str, v: u32) {            self.dwords.insert((hive == Hive::Machine, key.to_lowercase(), name.to_string()), v);        }    }    fn known_name(k: Known) -> &'static str {        match k {            Known::ProgramFiles => "pf",            Known::ProgramFilesCommon => "common",            Known::UserProgramFilesCommon => "user",            Known::Documents => "docs",        }    }    impl System for Fake {        fn var(&self, name: &str) -> Option<String> {            self.vars.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.clone())        }        fn known(&self, folder: Known) -> Option<PathBuf> {            self.known.get(known_name(folder)).cloned()        }        fn reg_string(&self, hive: Hive, key: &str, value: &str) -> Option<String> {            self.strings.get(&(hive == Hive::Machine, key.to_lowercase(), value.to_string())).cloned()        }        fn reg_dword(&self, hive: Hive, key: &str, value: &str) -> Option<u32> {            self.dwords.get(&(hive == Hive::Machine, key.to_lowercase(), value.to_string())).copied()        }        fn reg_subkeys(&self, hive: Hive, key: &str) -> Vec<String> {            let prefix = format!("{}\\", key.to_lowercase());            let mut out: Vec<String> = self                .strings                .keys()                .chain(self.dwords.keys())                .filter(|(m, k, _)| *m == (hive == Hive::Machine) && k.starts_with(&prefix))                .filter_map(|(_, k, _)| k[prefix.len()..].split('\\').next().map(str::to_string))                .collect();            out.sort();            out.dedup();            out        }    }    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-folders-{name}-{}", std::process::id()));        let _ = std::fs::remove_dir_all(&d);        std::fs::create_dir_all(&d).unwrap();        d    }    fn mk(p: &Path) -> PathBuf {        std::fs::create_dir_all(p).unwrap();        p.to_path_buf()    }    /// A made-up PC under `root`: Program Files, Common Files, a user's folders and Documents, with FL Studio in it.    pub fn fake_pc(root: &Path) -> Fake {        let pf = mk(&root.join("Program Files"));        let common = mk(&pf.join("Common Files"));        let user = root.join("Users").join("me").join("AppData").join("Local");        let mut f = Fake::default();        f.known.insert("pf", pf.clone());        f.known.insert("common", common.clone());        f.known.insert("user", user.join("Programs").join("Common"));        f.known.insert("docs", root.join("Users").join("me").join("Documents"));        f.vars.insert("LOCALAPPDATA".into(), user.to_string_lossy().into());        f.vars.insert("ProgramFiles".into(), pf.to_string_lossy().into());        f    }    #[test]    fn every_default_folder_from_the_environment_known_folders_and_registry() {        let root = tmp("defaults");        let mut f = fake_pc(&root);        let pf = f.known["pf"].clone();        let common = f.known["common"].clone();        let user = f.known["user"].clone();        let docs = f.known["docs"].clone();        for p in [            common.join("VST3"),            user.join("VST3"),            common.join("VST2"),            common.join("Steinberg").join("VST2"),            pf.join("VSTPlugins"),            pf.join("Steinberg").join("VstPlugins"),            pf.join("Native Instruments").join("VSTPlugins 64 bit"),            pf.join("Cakewalk").join("VstPlugins"),            root.join("D").join("VstPlugins"),            root.join("E").join("UserVst"),            // FL Studio: three versions, one without a VST folder, and its Fruity folders (never listed).            pf.join("Image-Line").join("FL Studio 20").join("Plugins").join("VST"),            pf.join("Image-Line").join("FL Studio 21").join("Plugins").join("VST"),            pf.join("Image-Line").join("FL Studio 2025").join("Plugins").join("Fruity").join("Effects"),            pf.join("Image-Line").join("FL Studio 2024").join("Plugins").join("VST"),            root.join("Studio").join("More plugins"),            root.join("Studio").join("Unticked in FL"),            docs.join("Image-Line").join("FL Studio").join("Plugins"),            common.join("Avid").join("Audio").join("Plug-Ins"),        ] {            mk(&p);        }        // Not in the list: Image-Line folders that aren't an FL Studio version, and a default folder that doesn't exist.        mk(&pf.join("Image-Line").join("Shared").join("Plugins").join("VST"));        mk(&pf.join("Image-Line").join("FL Studio ASIO").join("Plugins").join("VST"));        f.string(Hive::Machine, r"SOFTWARE\VST", "VSTPluginsPath", &root.join("D").join("VstPlugins").to_string_lossy());        f.vars.insert("JWVSTHOME".into(), root.join("E").to_string_lossy().into());        f.string(Hive::User, r"SOFTWARE\VST", "VSTPluginsPath", r"%JWVSTHOME%\UserVst");        // FL Studio's own list: Fruity (skipped), the shared VST 3 folder (already listed), one the user added there, one        // they unticked there, and its own %FLPath% VST folder.        let fl = pf.join("Image-Line").join("FL Studio 2025");        f.string(Hive::User, r"Software\Image-Line\Shared\Paths", "Install path", &fl.to_string_lossy());        let list = r"Software\Image-Line\Shared\Plugin search paths\List";        let entries: [(&str, String, u32, u32, u32); 5] = [            ("0", r"%FLPath%\Plugins\Fruity\Effects\".to_string(), 2, 1, 0),            ("1", format!("{}\\", common.join("VST3").display()), 7, 1, 0),            ("2", format!("{}\\", root.join("Studio").join("More plugins").display()), 0, 1, 1),            ("3", root.join("Studio").join("Unticked in FL").display().to_string(), 0, 0, 1),            ("10", r"%FLPath%\Plugins\VST\".to_string(), 0, 1, 0),        ];        for (k, path, class, selected, custom) in entries {            let key = format!(r"{list}\{k}");            f.string(Hive::User, &key, "path", &path);            f.dword(Hive::User, &key, "plugclass", class);            f.dword(Hive::User, &key, "selected", selected);            f.dword(Hive::User, &key, "custom", custom);        }        f.string(Hive::Machine, r"SOFTWARE\Image-Line\Shared\Paths", "VST plugins", &common.join("VST2").to_string_lossy());        // Its plugin database names a plugin in the user's Documents folder (counted) and Fruity ones (not).        let db = mk(&docs.join("Image-Line").join("FL Studio").join("Presets").join("Plugin database").join("Installed").join("Effects").join("VST"));        std::fs::write(            db.join("Old Delay.nfo"),            format!("fileversion=2\nps_name=Old Delay\nps_files=1\nps_file_filename_0={}\\Old Delay.dll\n", docs.join("Image-Line").join("FL Studio").join("Plugins").display()),        )        .unwrap();        let fruity = mk(&db.parent().unwrap().join("Fruity"));        std::fs::write(fruity.join("Fruity Delay.nfo"), "ps_file_filename_0=%FLPath%\\Plugins\\Fruity\\Effects\\Fruity Delay\\Fruity Delay_x64.dll\n").unwrap();        let found = defaults(&f);        let rel = |p: &Path| p.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/");        let got: Vec<(String, &str)> = found.iter().map(|x| (rel(&x.path), x.kind.label())).collect();        let want: Vec<(String, &str)> = [            ("Program Files/Common Files/VST3", "VST 3"),            ("Users/me/AppData/Local/Programs/Common/VST3", "VST 3"),            ("Program Files/Common Files/VST2", "VST 2"),            ("Program Files/Common Files/Steinberg/VST2", "VST 2"),            ("Program Files/VSTPlugins", "VST 2"),            ("Program Files/Steinberg/VstPlugins", "VST 2"),            ("Program Files/Native Instruments/VSTPlugins 64 bit", "VST 2"),            ("Program Files/Cakewalk/VstPlugins", "VST 2"),            ("D/VstPlugins", "VST 2"),            ("E/UserVst", "VST 2"),            ("Program Files/Image-Line/FL Studio 20/Plugins/VST", "FL Studio"),            ("Program Files/Image-Line/FL Studio 2024/Plugins/VST", "FL Studio"),            ("Program Files/Image-Line/FL Studio 21/Plugins/VST", "FL Studio"),            ("Studio/More plugins", "FL Studio"),            ("Users/me/Documents/Image-Line/FL Studio/Plugins", "FL Studio"),        ]        .iter()        .map(|(p, k)| (p.to_string(), *k))        .collect();        assert_eq!(got, want);        assert_eq!(found.iter().find(|x| rel(&x.path) == "Studio/More plugins").unwrap().from, "added in FL Studio's plugin manager");        // Never a hard-coded drive: with no known folders and no variables, nothing at all.        assert!(defaults(&Fake::default()).is_empty());        // Known folders missing, the environment still finds them.        let mut env_only = Fake::default();        env_only.vars.insert("CommonProgramW6432".into(), common.to_string_lossy().into());        env_only.vars.insert("LOCALAPPDATA".into(), f.vars["LOCALAPPDATA"].clone());        let got: Vec<String> = defaults(&env_only).iter().map(|x| rel(&x.path)).collect();        assert_eq!(&got[..2], ["Program Files/Common Files/VST3", "Users/me/AppData/Local/Programs/Common/VST3"]);        let _ = std::fs::remove_dir_all(&root);    }    #[test]    fn the_list_is_tidy() {        let exists = |_: &Path| true;        let f = |p: &str, kind| Folder { path: PathBuf::from(p), kind, from: "test" };        let out = tidy(            vec![                f(r"X:\Plugins\VST3\", Kind::Vst3),                f(r"x:\plugins\vst3", Kind::FlStudio),                f(r"X:\Plugins\VST3\Vendor", Kind::FlStudio),                f(r"X:\Plugins\VST3x", Kind::Vst2),                f(r"relative\folder", Kind::Vst2),                f(r"X:\FL\Plugins\Fruity\Effects", Kind::FlStudio),                f(r"X:\Program Files\Common Files\Avid\Audio\Plug-Ins", Kind::Vst2),                f("", Kind::Vst2),                f(r"Y:\", Kind::Added),            ],            &exists,        );        let got: Vec<_> = out.iter().map(|f| (f.path.to_string_lossy().to_string(), f.kind)).collect();        assert_eq!(got, [(r"X:\Plugins\VST3".to_string(), Kind::Vst3), (r"X:\Plugins\VST3x".into(), Kind::Vst2), (r"Y:\".into(), Kind::Added)]);        assert!(within(Path::new(r"X:\A\B"), Path::new(r"x:\a\")) && !within(Path::new(r"X:\AB"), Path::new(r"X:\A")));    }    #[test]    fn percent_names_expand() {        let mut f = Fake::default();        f.vars.insert("ProgramFiles".into(), r"X:\PF".into());        assert_eq!(expand(r"%ProgramFiles%\VST", &f, None), r"X:\PF\VST");        assert_eq!(expand(r"%FLPath%\Plugins\VST\", &f, Some(Path::new(r"X:\FL"))), r"X:\FL\Plugins\VST\");        assert_eq!(expand(r"%Nope%\x", &f, None), r"%Nope%\x");        assert_eq!(expand("100% sure", &f, None), "100% sure");        assert_eq!(expand("%%x", &f, None), "%%x");    }}