Skip to main content

maolan_engine/plugins/
mod.rs

1pub mod clap_proc;
2pub mod ipc;
3#[cfg(unix)]
4pub mod lv2_proc;
5pub mod types;
6pub mod vst3_proc;
7
8pub use types::*;
9
10use serde::de::DeserializeOwned;
11
12#[derive(serde::Deserialize)]
13struct ScanDiagnostic {
14    message: String,
15    plugin_uri: Option<String>,
16    plugin_name: Option<String>,
17    bundle_uri: Option<String>,
18}
19
20#[derive(serde::Deserialize)]
21struct ScanOutput<T> {
22    data: T,
23    errors: Vec<ScanDiagnostic>,
24    warnings: Vec<ScanDiagnostic>,
25}
26
27use crate::message::PluginKind;
28
29pub fn resolve_plugin_identifier(kind: PluginKind, identifier: &str) -> Result<String, String> {
30    if identifier.is_empty() {
31        return Err("plugin identifier is empty".to_string());
32    }
33    if identifier.contains('/')
34        || identifier.contains('\\')
35        || identifier.contains("::")
36        || identifier.contains('#')
37        || identifier.contains("://")
38        || identifier.starts_with("file:")
39        || std::path::Path::new(identifier).exists()
40    {
41        return Ok(identifier.to_string());
42    }
43
44    match kind {
45        PluginKind::Clap => {
46            let plugins = scan_plugins::<ClapPluginInfo>("clap")
47                .map_err(|e| format!("failed to scan CLAP plugins: {e}"))?;
48            plugins
49                .into_iter()
50                .find(|p| !p.id.is_empty() && p.id == identifier)
51                .map(|p| p.path)
52                .ok_or_else(|| format!("CLAP plugin ID not found: {identifier}"))
53        }
54        PluginKind::Vst3 => {
55            let plugins = scan_plugins::<Vst3PluginInfo>("vst3")
56                .map_err(|e| format!("failed to scan VST3 plugins: {e}"))?;
57            plugins
58                .into_iter()
59                .find(|p| !p.id.is_empty() && p.id == identifier)
60                .map(|p| p.path)
61                .ok_or_else(|| format!("VST3 plugin ID not found: {identifier}"))
62        }
63        #[cfg(unix)]
64        PluginKind::Lv2 => {
65            let plugins = scan_plugins::<Lv2PluginInfo>("lv2")
66                .map_err(|e| format!("failed to scan LV2 plugins: {e}"))?;
67            plugins
68                .into_iter()
69                .find(|p| p.uri == identifier)
70                .map(|p| p.uri)
71                .ok_or_else(|| format!("LV2 plugin URI not found: {identifier}"))
72        }
73    }
74}
75
76pub fn scan_plugins<T: DeserializeOwned>(format: &str) -> Result<Vec<T>, String> {
77    let host_bin = ipc::find_plugin_host_binary().ok_or("maolan-plugin-host binary not found")?;
78
79    let mut cmd = std::process::Command::new(&host_bin);
80    cmd.arg("--scan")
81        .arg("--format")
82        .arg(format)
83        .arg("--path")
84        .arg("--system");
85    ipc::append_parent_log_level(&mut cmd);
86    ipc::hide_console_window(&mut cmd);
87
88    let output = cmd
89        .output()
90        .map_err(|e| format!("failed to spawn plugin-host scanner: {e}"))?;
91
92    if !output.status.success() {
93        let stderr = String::from_utf8_lossy(&output.stderr);
94        return Err(format!(
95            "plugin-host scanner exited with code {:?}: {stderr}",
96            output.status.code()
97        ));
98    }
99
100    let json = String::from_utf8_lossy(&output.stdout);
101    let parsed: ScanOutput<Vec<T>> =
102        serde_json::from_str(&json).map_err(|e| format!("failed to parse scan JSON: {e}"))?;
103
104    for error in &parsed.errors {
105        tracing::error!(
106            message = %error.message,
107            plugin_uri = ?error.plugin_uri,
108            plugin_name = ?error.plugin_name,
109            bundle_uri = ?error.bundle_uri,
110            "plugin scan error"
111        );
112    }
113    for warning in &parsed.warnings {
114        tracing::warn!(
115            message = %warning.message,
116            plugin_uri = ?warning.plugin_uri,
117            plugin_name = ?warning.plugin_name,
118            bundle_uri = ?warning.bundle_uri,
119            "plugin scan warning"
120        );
121    }
122
123    Ok(parsed.data)
124}
125
126#[cfg(test)]
127mod tests {
128    use super::ScanOutput;
129
130    #[test]
131    fn scan_output_parses_wrapper() {
132        let json = r#"{
133            "errors": [
134                {
135                    "message": "error: failed to open manifest.ttl",
136                    "bundle_uri": "file:///tmp/broken.lv2/"
137                }
138            ],
139            "warnings": [
140                {
141                    "message": "warning: duplicate version",
142                    "plugin_uri": "http://example.com/plugin"
143                }
144            ],
145            "data": [{"name": "Test", "path": "/tmp/test.clap", "capabilities": null}]
146        }"#;
147        let output: ScanOutput<Vec<serde_json::Value>> = serde_json::from_str(json).unwrap();
148        assert_eq!(output.errors.len(), 1);
149        assert_eq!(
150            output.errors[0].message,
151            "error: failed to open manifest.ttl"
152        );
153        assert_eq!(
154            output.errors[0].bundle_uri,
155            Some("file:///tmp/broken.lv2/".to_string())
156        );
157        assert_eq!(output.warnings.len(), 1);
158        assert_eq!(
159            output.warnings[0].plugin_uri,
160            Some("http://example.com/plugin".to_string())
161        );
162        assert_eq!(output.data.len(), 1);
163        assert_eq!(output.data[0]["name"], "Test");
164    }
165}