Skip to main content

eov_plugin_api/
manifest.rs

1//! Plugin manifest (`plugin.toml`) parsing and validation.
2//!
3//! ```toml
4//! id = "example_plugin"              # ^[a-z0-9][a-z0-9_]{0,63}$
5//! name = "Example Plugin"
6//! version = "1.0.0"                  # semantic version
7//! description = "Optional description shown in the Plugins panel"
8//! repository = "https://github.com/example/example-plugin"
9//! api = ">=1.0, <2"                  # optional eov-plugin-api requirement
10//!
11//! [environment]                      # optional; defaults to any eov version
12//! version = ">=1.0.0, <2.0.0"        # eov application version requirement
13//!
14//! [icon]                             # optional, for the Plugins panel
15//! kind = "svg"
16//! data = "<svg xmlns='http://www.w3.org/2000/svg'/>"
17//!
18//! [ui]                               # optional
19//! slint = ">=1.17"                   # Slint version the .slint files need
20//!
21//! [[slide_formats]]                  # optional, repeatable
22//! id = "gradient"                    # ^[a-z0-9][a-z0-9_-]{0,63}$, unique here
23//! name = "Synthetic gradient slide"  # shown in the file picker
24//! extensions = ["gradient"]          # file extensions, without the dot
25//! schemes = []                       # URI schemes (`omero` for omero://…)
26//! ```
27//!
28//! The plugin library must be named after the id (`lib<id>.so`,
29//! `lib<id>.dylib` or `<id>.dll`) and sit next to `plugin.toml`. Unknown keys
30//! are ignored so that manifests written for newer hosts still load (an eov
31//! without slide sources runs a plugin with `[[slide_formats]]`, without its
32//! formats).
33
34use crate::{IconDescriptor, PluginError, PluginResult};
35use semver::{Version, VersionReq};
36use serde::{Deserialize, Serialize};
37use std::path::{Component, Path};
38
39/// Requirements on the host application.
40#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
41pub struct PluginEnvironment {
42    /// eov version requirement (semver range).
43    pub version: String,
44}
45
46impl Default for PluginEnvironment {
47    /// Manifests without an `[environment]` table accept any eov version; the
48    /// plugin-API check at load time still applies.
49    fn default() -> Self {
50        Self {
51            version: "*".to_string(),
52        }
53    }
54}
55
56/// UI requirements.
57#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
58pub struct PluginUi {
59    /// Slint version requirement for the plugin's `.slint` surfaces.
60    #[serde(default)]
61    pub slint: Option<String>,
62}
63
64/// Most `[[slide_formats]]` a manifest may declare.
65pub const MAX_SLIDE_FORMATS: usize = 16;
66
67/// URI schemes no plugin may claim: local files and eov's own links.
68pub const RESERVED_SCHEMES: &[&str] = &["file", "eov"];
69
70/// A slide format the plugin reads, declared so that eov
71/// knows its file extensions and URI schemes without running plugin code:
72/// the file picker, the series bar, folder scans and `eov batch` offer
73/// them, and opening a matching slide asks the plugin's slide source.
74///
75/// eov's own readers keep the extensions they read (`svs`, `tif`, `dcm`,
76/// …): a plugin claiming one of them is asked only for files those readers
77/// cannot open.
78#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
79pub struct SlideFormatSpec {
80    /// Unique within the plugin (`^[a-z0-9][a-z0-9_-]{0,63}$`); the slide
81    /// source learns which format matched from it.
82    pub id: String,
83    /// Shown in the file picker, e.g. "Philips iSyntax".
84    pub name: String,
85    /// File extensions without the dot (`["isyntax"]`): 1–16 ASCII letters
86    /// or digits, matched without regard to case.
87    #[serde(default)]
88    pub extensions: Vec<String>,
89    /// URI schemes for slides that are not local files (`["omero"]` claims
90    /// `omero://…`): a letter, then letters, digits, `+`, `-` or `.`, 2–32
91    /// characters in all. `file` and `eov` are reserved.
92    #[serde(default)]
93    pub schemes: Vec<String>,
94}
95
96impl SlideFormatSpec {
97    /// The extensions in lower case.
98    pub fn normalized_extensions(&self) -> Vec<String> {
99        self.extensions
100            .iter()
101            .map(|ext| ext.to_ascii_lowercase())
102            .collect()
103    }
104
105    /// The schemes in lower case.
106    pub fn normalized_schemes(&self) -> Vec<String> {
107        self.schemes
108            .iter()
109            .map(|scheme| scheme.to_ascii_lowercase())
110            .collect()
111    }
112
113    fn validate(&self) -> Result<(), String> {
114        let mut id = self.id.chars();
115        if !(matches!(id.next(), Some(c) if c.is_ascii_lowercase() || c.is_ascii_digit())
116            && self.id.len() <= 64
117            && id.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-'))
118        {
119            return Err(format!(
120                "slide format ids are 1–64 lowercase letters, digits, '_' or '-', got '{}'",
121                self.id
122            ));
123        }
124        if self.name.trim().is_empty() || self.name.chars().count() > 100 {
125            return Err(format!(
126                "slide format '{}' needs a name of 1–100 characters",
127                self.id
128            ));
129        }
130        if self.extensions.is_empty() && self.schemes.is_empty() {
131            return Err(format!(
132                "slide format '{}' declares neither extensions nor schemes",
133                self.id
134            ));
135        }
136        if self.extensions.len() > 32 || self.schemes.len() > 8 {
137            return Err(format!(
138                "slide format '{}' declares too many extensions (at most 32) or schemes (at most 8)",
139                self.id
140            ));
141        }
142        for extension in &self.extensions {
143            if extension.is_empty()
144                || extension.len() > 16
145                || !extension.chars().all(|c| c.is_ascii_alphanumeric())
146            {
147                return Err(format!(
148                    "slide format '{}': extensions are 1–16 letters or digits without the dot, got '{extension}'",
149                    self.id
150                ));
151            }
152        }
153        for scheme in &self.schemes {
154            let mut chars = scheme.chars();
155            let valid = matches!(chars.next(), Some(c) if c.is_ascii_alphabetic())
156                && (2..=32).contains(&scheme.len())
157                && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
158            if !valid {
159                return Err(format!(
160                    "slide format '{}': '{scheme}' is not a URI scheme (a letter, then letters, digits, '+', '-' or '.', 2–32 characters)",
161                    self.id
162                ));
163            }
164            if RESERVED_SCHEMES
165                .iter()
166                .any(|reserved| scheme.eq_ignore_ascii_case(reserved))
167            {
168                return Err(format!(
169                    "slide format '{}': the '{scheme}' scheme is eov's own",
170                    self.id
171                ));
172            }
173        }
174        Ok(())
175    }
176}
177
178/// The parsed contents of a `plugin.toml` manifest.
179#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
180pub struct PluginManifest {
181    /// Unique, stable identifier (`^[a-z0-9][a-z0-9_]{0,63}$`).
182    pub id: String,
183    /// Human-readable name shown in the UI.
184    pub name: String,
185    /// Semantic version of the plugin.
186    pub version: String,
187    #[serde(default)]
188    pub description: Option<String>,
189    #[serde(default)]
190    pub repository: Option<String>,
191    /// eov-plugin-api requirement, e.g. `">=1.0, <2"`. When absent the API
192    /// version embedded in the library is the only check.
193    #[serde(default)]
194    pub api: Option<String>,
195    /// Icon for the Plugins panel.
196    #[serde(default)]
197    pub icon: Option<IconDescriptor>,
198    /// Host application requirements.
199    #[serde(default)]
200    pub environment: PluginEnvironment,
201    /// Whether the manifest had an `[environment]` table.
202    #[serde(skip)]
203    pub declares_environment: bool,
204    #[serde(default)]
205    pub ui: PluginUi,
206    /// Slide formats the plugin reads.
207    #[serde(default)]
208    pub slide_formats: Vec<SlideFormatSpec>,
209}
210
211/// Name of the manifest file inside each plugin directory.
212pub const MANIFEST_FILENAME: &str = "plugin.toml";
213
214/// Whether `id` is a valid plugin id: lowercase ASCII letters, digits and
215/// `_`, starting with a letter or digit, at most 64 characters.
216pub fn is_valid_plugin_id(id: &str) -> bool {
217    let mut chars = id.chars();
218    matches!(chars.next(), Some(c) if c.is_ascii_lowercase() || c.is_ascii_digit())
219        && id.len() <= 64
220        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
221}
222
223/// Whether `path` is relative and stays inside its base directory
224/// (no root, drive prefix or `..` component).
225pub fn is_contained_relative_path(path: &Path) -> bool {
226    !path.as_os_str().is_empty()
227        && path
228            .components()
229            .all(|c| matches!(c, Component::Normal(_) | Component::CurDir))
230}
231
232impl PluginManifest {
233    /// Parses and validates a manifest. `plugin_id_hint` names the package
234    /// in error messages when the id itself is unusable.
235    pub fn from_toml(toml_str: &str, plugin_id_hint: &str) -> PluginResult<Self> {
236        let mut manifest: Self = toml::from_str(toml_str).map_err(|e| PluginError::Manifest {
237            plugin_id: plugin_id_hint.to_string(),
238            message: format!("TOML parse error: {e}"),
239        })?;
240        manifest.declares_environment = toml_str
241            .parse::<toml::Table>()
242            .map(|table| table.contains_key("environment"))
243            .unwrap_or(false);
244        manifest.validate()?;
245        Ok(manifest)
246    }
247
248    /// Loads a manifest from a file path.
249    pub fn from_file(path: &Path) -> PluginResult<Self> {
250        let dir_name = path
251            .parent()
252            .and_then(|p| p.file_name())
253            .and_then(|n| n.to_str())
254            .unwrap_or("<unknown>");
255        let contents = std::fs::read_to_string(path).map_err(|e| PluginError::Manifest {
256            plugin_id: dir_name.to_string(),
257            message: format!("failed to read {}: {e}", path.display()),
258        })?;
259        Self::from_toml(&contents, dir_name)
260    }
261
262    fn error(&self, message: impl Into<String>) -> PluginError {
263        PluginError::Manifest {
264            plugin_id: self.id.clone(),
265            message: message.into(),
266        }
267    }
268
269    fn validate(&self) -> PluginResult<()> {
270        if !is_valid_plugin_id(&self.id) {
271            return Err(self.error(format!(
272                "'id' must be 1–64 lowercase letters, digits or '_' and start with a letter or digit, got '{}'",
273                self.id
274            )));
275        }
276        if self.name.trim().is_empty() || self.name.len() > 100 {
277            return Err(self.error("'name' must be 1–100 characters"));
278        }
279        Version::parse(&self.version)
280            .map_err(|e| self.error(format!("'version' must be a semantic version: {e}")))?;
281        VersionReq::parse(&self.environment.version).map_err(|e| {
282            self.error(format!(
283                "'environment.version' must be a semver requirement: {e}"
284            ))
285        })?;
286        if let Some(api) = &self.api {
287            VersionReq::parse(api)
288                .map_err(|e| self.error(format!("'api' must be a semver requirement: {e}")))?;
289        }
290        if let Some(slint) = &self.ui.slint {
291            VersionReq::parse(slint)
292                .map_err(|e| self.error(format!("'ui.slint' must be a semver requirement: {e}")))?;
293        }
294        if self.description.as_ref().is_some_and(|d| d.len() > 2000) {
295            return Err(self.error("'description' must be at most 2000 characters"));
296        }
297        match &self.icon {
298            Some(IconDescriptor::File { path }) if !is_contained_relative_path(path) => {
299                return Err(self.error(format!(
300                    "icon file path must be relative and stay inside the package, got '{}'",
301                    path.display()
302                )));
303            }
304            Some(IconDescriptor::Svg { data }) if data.len() > 64 * 1024 => {
305                return Err(self.error("inline icon SVG must be at most 64 KiB"));
306            }
307            _ => {}
308        }
309        if self.slide_formats.len() > MAX_SLIDE_FORMATS {
310            return Err(self.error(format!(
311                "at most {MAX_SLIDE_FORMATS} [[slide_formats]] may be declared"
312            )));
313        }
314        let mut ids = std::collections::BTreeSet::new();
315        for format in &self.slide_formats {
316            format.validate().map_err(|message| self.error(message))?;
317            if !ids.insert(format.id.as_str()) {
318                return Err(
319                    self.error(format!("slide format id '{}' is declared twice", format.id))
320                );
321            }
322        }
323        Ok(())
324    }
325
326    /// Whether the host's plugin-API version satisfies `api`.
327    pub fn accepts_api(&self, api_version: &Version) -> bool {
328        self.api
329            .as_deref()
330            .and_then(|req| VersionReq::parse(req).ok())
331            .is_none_or(|req| req.matches(api_version))
332    }
333
334    /// Whether the eov version satisfies `environment.version`.
335    pub fn accepts_host(&self, host_version: &Version) -> bool {
336        VersionReq::parse(&self.environment.version)
337            .map(|req| req.matches(host_version))
338            .unwrap_or(false)
339    }
340
341    /// Whether the host's Slint version satisfies `ui.slint`.
342    pub fn accepts_slint(&self, slint_version: &Version) -> bool {
343        self.ui
344            .slint
345            .as_deref()
346            .and_then(|req| VersionReq::parse(req).ok())
347            .is_none_or(|req| req.matches(slint_version))
348    }
349
350    /// Checks that referenced files exist.
351    pub fn validate_files(&self, plugin_root: &Path) -> PluginResult<()> {
352        if let Some(IconDescriptor::File { path }) = &self.icon {
353            let icon_path = plugin_root.join(path);
354            if !icon_path.exists() {
355                return Err(PluginError::MissingFile {
356                    plugin_id: self.id.clone(),
357                    path: icon_path,
358                });
359            }
360        }
361        Ok(())
362    }
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368
369    const VALID_TOML: &str = r#"
370id = "test_plugin"
371name = "Test Plugin"
372version = "1.0.0"
373description = "A test plugin"
374repository = "https://github.com/example/test-plugin"
375api = ">=1.0, <2"
376
377[environment]
378version = ">=1.0.0, <2.0.0"
379
380[icon]
381kind = "svg"
382data = "<svg/>"
383
384[ui]
385slint = ">=1.17"
386"#;
387
388    fn parse(toml: &str) -> PluginResult<PluginManifest> {
389        PluginManifest::from_toml(toml, "hint")
390    }
391
392    #[test]
393    fn parse_valid_manifest() {
394        let m = parse(VALID_TOML).unwrap();
395        assert_eq!(m.id, "test_plugin");
396        assert_eq!(m.name, "Test Plugin");
397        assert_eq!(m.description.as_deref(), Some("A test plugin"));
398        assert!(m.declares_environment);
399        assert!(m.accepts_api(&Version::new(1, 3, 0)));
400        assert!(!m.accepts_api(&Version::new(2, 0, 0)));
401        assert!(m.accepts_host(&Version::new(1, 0, 0)));
402        assert!(m.accepts_slint(&Version::new(1, 17, 1)));
403        assert!(!m.accepts_slint(&Version::new(1, 16, 0)));
404    }
405
406    #[test]
407    fn environment_is_optional() {
408        // PLG-4: cellaris shipped without [environment].
409        let m = parse(
410            r#"
411id = "cellaris"
412name = "Cellaris"
413version = "1.0.0"
414"#,
415        )
416        .unwrap();
417        assert!(!m.declares_environment);
418        assert!(m.accepts_host(&Version::new(1, 2, 3)));
419        assert!(m.accepts_api(&Version::new(1, 0, 0)));
420    }
421
422    #[test]
423    fn manifests_of_older_hosts_still_parse() {
424        // Fields from the 0.x format are ignored.
425        let m = parse(
426            r#"
427id = "legacy"
428name = "Legacy"
429version = "0.4.9"
430entry_ui = "ui/panel.slint"
431entry_component = "Panel"
432
433[[toolbar_buttons]]
434button_id = "x"
435tooltip = "X"
436action_id = "x"
437
438[environment]
439version = ">=0.4.1"
440"#,
441        )
442        .unwrap();
443        assert_eq!(m.id, "legacy");
444        // The host range admits 1.0; the ABI check at load time rejects it.
445        assert!(m.accepts_host(&Version::new(1, 0, 0)));
446    }
447
448    #[test]
449    fn ids_are_validated() {
450        for bad in [
451            "",
452            "Upper",
453            "has-dash",
454            "has:colon",
455            "C:evil",
456            "a/b",
457            "../x",
458            "_lead",
459            &"x".repeat(65),
460        ] {
461            let toml = format!("id = \"{bad}\"\nname = \"N\"\nversion = \"1.0.0\"\n");
462            assert!(parse(&toml).is_err(), "accepted '{bad}'");
463        }
464        for good in ["a", "eovae", "gamepad_2", "0day"] {
465            assert!(is_valid_plugin_id(good), "rejected '{good}'");
466        }
467    }
468
469    #[test]
470    fn versions_and_requirements_are_validated() {
471        assert!(parse("id = \"a\"\nname = \"A\"\nversion = \"one\"\n").is_err());
472        assert!(
473            parse("id = \"a\"\nname = \"A\"\nversion = \"1.0.0\"\napi = \"not a req\"\n").is_err()
474        );
475        assert!(
476            parse(
477                "id = \"a\"\nname = \"A\"\nversion = \"1.0.0\"\n[environment]\nversion = \"??\"\n"
478            )
479            .is_err()
480        );
481        assert!(parse("id = \"a\"\nname = \"\"\nversion = \"1.0.0\"\n").is_err());
482    }
483
484    #[test]
485    fn icon_paths_must_stay_inside_the_package() {
486        for bad in ["/etc/icon.png", "../icon.png", "a/../../icon.png"] {
487            let toml = format!(
488                "id = \"a\"\nname = \"A\"\nversion = \"1.0.0\"\n[icon]\nkind = \"file\"\npath = \"{bad}\"\n"
489            );
490            assert!(parse(&toml).is_err(), "accepted '{bad}'");
491        }
492        let toml = "id = \"a\"\nname = \"A\"\nversion = \"1.0.0\"\n[icon]\nkind = \"file\"\npath = \"assets/icon.png\"\n";
493        let m = parse(toml).unwrap();
494        assert!(matches!(
495            m.validate_files(Path::new("/nonexistent")),
496            Err(PluginError::MissingFile { .. })
497        ));
498    }
499
500    #[test]
501    fn readme_example_parses() {
502        // Keep the documented format honest (PLG-4).
503        let docs = include_str!("manifest.rs");
504        let example: String = docs
505            .lines()
506            .skip_while(|line| !line.starts_with("//! ```toml"))
507            .skip(1)
508            .take_while(|line| !line.starts_with("//! ```"))
509            .map(|line| line.trim_start_matches("//!").trim_start_matches(' '))
510            .map(|line| format!("{line}\n"))
511            .collect();
512        let m = parse(&example).unwrap();
513        assert_eq!(m.id, "example_plugin");
514        assert!(m.declares_environment);
515        assert_eq!(m.slide_formats.len(), 1);
516        assert_eq!(m.slide_formats[0].extensions, ["gradient"]);
517    }
518
519    #[test]
520    fn slide_formats_are_declared_and_validated() {
521        let base = "id = \"reader\"\nname = \"Reader\"\nversion = \"1.1.0\"\n";
522        let m = parse(&format!(
523            "{base}[[slide_formats]]\nid = \"isyntax\"\nname = \"Philips iSyntax\"\nextensions = [\"iSyntax\"]\n\
524             [[slide_formats]]\nid = \"omero\"\nname = \"OMERO\"\nschemes = [\"omero\", \"omero+https\"]\n"
525        ))
526        .unwrap();
527        assert_eq!(m.slide_formats.len(), 2);
528        assert_eq!(m.slide_formats[0].normalized_extensions(), ["isyntax"]);
529        assert_eq!(
530            m.slide_formats[1].normalized_schemes(),
531            ["omero", "omero+https"]
532        );
533        // Manifests without formats have none.
534        assert!(parse(base).unwrap().slide_formats.is_empty());
535
536        for bad in [
537            // Neither extensions nor schemes.
538            "[[slide_formats]]\nid = \"a\"\nname = \"A\"\n",
539            // Ids, names, extensions and schemes are checked.
540            "[[slide_formats]]\nid = \"Bad Id\"\nname = \"A\"\nextensions = [\"a\"]\n",
541            "[[slide_formats]]\nid = \"a\"\nname = \"\"\nextensions = [\"a\"]\n",
542            "[[slide_formats]]\nid = \"a\"\nname = \"A\"\nextensions = [\".svs\"]\n",
543            "[[slide_formats]]\nid = \"a\"\nname = \"A\"\nextensions = [\"ome.zarr\"]\n",
544            "[[slide_formats]]\nid = \"a\"\nname = \"A\"\nschemes = [\"c\"]\n",
545            "[[slide_formats]]\nid = \"a\"\nname = \"A\"\nschemes = [\"9p\"]\n",
546            "[[slide_formats]]\nid = \"a\"\nname = \"A\"\nschemes = [\"file\"]\n",
547            "[[slide_formats]]\nid = \"a\"\nname = \"A\"\nschemes = [\"EOV\"]\n",
548            // Duplicate ids.
549            "[[slide_formats]]\nid = \"a\"\nname = \"A\"\nextensions = [\"a\"]\n\
550             [[slide_formats]]\nid = \"a\"\nname = \"B\"\nextensions = [\"b\"]\n",
551        ] {
552            assert!(parse(&format!("{base}{bad}")).is_err(), "accepted:\n{bad}");
553        }
554    }
555}