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