par-term-config 0.14.1

Configuration system for par-term terminal emulator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Shader bundle manifest parsing and validation.

use serde::{Deserialize, Serialize};
use std::path::{Component, Path};

/// Manifest describing a shader bundle and its local assets.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShaderBundleManifest {
    pub shader: String,
    pub name: String,
    pub author: String,
    pub description: String,
    pub license: String,
    #[serde(default)]
    pub textures: Vec<String>,
    #[serde(default)]
    pub cubemaps: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub screenshot: Option<String>,
}

#[derive(Debug, Deserialize)]
struct RawShaderBundleManifest {
    shader: Option<String>,
    name: Option<String>,
    author: Option<String>,
    description: Option<String>,
    license: Option<String>,
    #[serde(default)]
    textures: Vec<String>,
    #[serde(default)]
    cubemaps: Vec<String>,
    #[serde(default)]
    screenshot: Option<String>,
}

impl ShaderBundleManifest {
    /// Parse a JSON manifest string and report all missing required fields together.
    ///
    /// # Errors
    ///
    /// Returns an error if `input` is not valid JSON for the manifest schema,
    /// or if any of `shader`, `name`, `author`, `description`, or `license` is
    /// absent or blank. Missing fields are reported in a single message rather
    /// than one at a time.
    pub fn from_json_str(input: &str) -> Result<Self, String> {
        let raw: RawShaderBundleManifest = serde_json::from_str(input)
            .map_err(|e| format!("parse shader bundle manifest: {e}"))?;
        let missing = missing_required_fields(
            raw.shader.as_deref(),
            raw.name.as_deref(),
            raw.author.as_deref(),
            raw.description.as_deref(),
            raw.license.as_deref(),
        );
        if !missing.is_empty() {
            return Err(format!(
                "missing required shader bundle manifest field(s): {}",
                missing.join(", ")
            ));
        }

        Ok(Self {
            shader: raw.shader.expect("checked required shader"),
            name: raw.name.expect("checked required name"),
            author: raw.author.expect("checked required author"),
            description: raw.description.expect("checked required description"),
            license: raw.license.expect("checked required license"),
            textures: raw.textures,
            cubemaps: raw.cubemaps,
            screenshot: raw.screenshot,
        })
    }

    /// Validate required fields are present and non-empty.
    ///
    /// # Errors
    ///
    /// Returns an error listing every blank field among `shader`, `name`,
    /// `author`, `description`, and `license`. A manifest obtained from
    /// [`Self::from_json_str`] always passes; this matters for manifests built
    /// or mutated through the public fields.
    pub fn validate_required_fields(&self) -> Result<(), String> {
        let missing = missing_required_fields(
            Some(&self.shader),
            Some(&self.name),
            Some(&self.author),
            Some(&self.description),
            Some(&self.license),
        );
        if missing.is_empty() {
            Ok(())
        } else {
            Err(format!(
                "missing required shader bundle manifest field(s): {}",
                missing.join(", ")
            ))
        }
    }

    /// Validate that manifest asset paths are relative to `bundle_dir` and exist.
    ///
    /// # Errors
    ///
    /// Returns an error if [`Self::validate_required_fields`] fails; if any
    /// `shader`, `textures`, `cubemaps`, or `screenshot` entry is blank,
    /// absolute, or contains a `..` component; if `shader` does not end in
    /// `.glsl`; or if a referenced file (or any face of a cubemap) is not
    /// present under `bundle_dir`.
    pub fn validate_paths(&self, bundle_dir: &Path) -> Result<(), String> {
        self.validate_required_fields()?;

        validate_relative_path("shader", &self.shader)?;
        if !self.shader.ends_with(".glsl") {
            return Err(
                "shader bundle manifest field `shader` must point to a .glsl file".to_string(),
            );
        }
        ensure_exists(bundle_dir, "shader", &self.shader)?;

        for texture in &self.textures {
            validate_relative_path("textures", texture)?;
            ensure_exists(bundle_dir, "textures", texture)?;
        }

        for cubemap in &self.cubemaps {
            validate_relative_path("cubemaps", cubemap)?;
            ensure_cubemap_faces_exist(bundle_dir, cubemap)?;
        }

        if let Some(screenshot) = &self.screenshot {
            validate_relative_path("screenshot", screenshot)?;
            ensure_exists(bundle_dir, "screenshot", screenshot)?;
        }

        Ok(())
    }
}

fn missing_required_fields(
    shader: Option<&str>,
    name: Option<&str>,
    author: Option<&str>,
    description: Option<&str>,
    license: Option<&str>,
) -> Vec<&'static str> {
    let mut missing = Vec::new();
    if shader.is_none_or(|value| value.trim().is_empty()) {
        missing.push("shader");
    }
    if name.is_none_or(|value| value.trim().is_empty()) {
        missing.push("name");
    }
    if author.is_none_or(|value| value.trim().is_empty()) {
        missing.push("author");
    }
    if description.is_none_or(|value| value.trim().is_empty()) {
        missing.push("description");
    }
    if license.is_none_or(|value| value.trim().is_empty()) {
        missing.push("license");
    }
    missing
}

fn validate_relative_path(field: &str, value: &str) -> Result<(), String> {
    let path = Path::new(value);
    let invalid_component = path.components().any(|component| {
        matches!(
            component,
            Component::ParentDir | Component::RootDir | Component::Prefix(_)
        )
    });
    if value.trim().is_empty() || path.is_absolute() || invalid_component {
        return Err(format!(
            "shader bundle manifest field `{field}` must be a non-empty relative path without '..'"
        ));
    }
    Ok(())
}

fn ensure_exists(bundle_dir: &Path, field: &str, value: &str) -> Result<(), String> {
    if bundle_dir.join(value).is_file() {
        Ok(())
    } else {
        Err(format!(
            "shader bundle manifest field `{field}` path is not a file: {value}"
        ))
    }
}

fn ensure_cubemap_faces_exist(bundle_dir: &Path, prefix: &str) -> Result<(), String> {
    const SUFFIXES: [&str; 6] = ["px", "nx", "py", "ny", "pz", "nz"];
    const EXTENSIONS: [&str; 4] = ["png", "jpg", "jpeg", "hdr"];

    for suffix in SUFFIXES {
        let found = EXTENSIONS.iter().any(|ext| {
            bundle_dir
                .join(format!("{prefix}-{suffix}.{ext}"))
                .is_file()
        });
        if !found {
            return Err(format!(
                "missing cubemap face for prefix `{prefix}` and suffix `{suffix}`"
            ));
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bundle_manifest_requires_author_and_description() {
        let json = r#"{
            "shader": "shader.glsl",
            "name": "Missing Fields",
            "license": "MIT"
        }"#;

        let err = ShaderBundleManifest::from_json_str(json)
            .expect_err("missing author and description should fail");

        assert!(err.contains("author"));
        assert!(err.contains("description"));
    }

    #[test]
    fn validates_bundle_manifest_paths_relative_to_bundle_dir() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::write(
            temp.path().join("shader.glsl"),
            "void mainImage(out vec4 c, in vec2 p){c=vec4(0.0);}",
        )
        .unwrap();
        std::fs::create_dir_all(temp.path().join("textures")).unwrap();
        std::fs::write(temp.path().join("textures/noise.png"), b"fake").unwrap();

        let manifest = ShaderBundleManifest {
            shader: "shader.glsl".to_string(),
            name: "Valid Bundle".to_string(),
            author: "par-term".to_string(),
            description: "A valid test bundle.".to_string(),
            license: "MIT".to_string(),
            textures: vec!["textures/noise.png".to_string()],
            cubemaps: Vec::new(),
            screenshot: None,
        };

        manifest.validate_paths(temp.path()).unwrap();
    }

    #[test]
    fn rejects_absolute_and_parent_bundle_paths() {
        let manifest = ShaderBundleManifest {
            shader: "/tmp/shader.glsl".to_string(),
            name: "Invalid Bundle".to_string(),
            author: "par-term".to_string(),
            description: "Invalid absolute shader path.".to_string(),
            license: "MIT".to_string(),
            textures: vec!["../noise.png".to_string()],
            cubemaps: Vec::new(),
            screenshot: None,
        };

        let err = manifest
            .validate_paths(std::path::Path::new("."))
            .expect_err("absolute shader path should fail");

        assert!(err.contains("relative path"));
    }

    #[test]
    fn rejects_shader_path_that_is_a_directory() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::create_dir(temp.path().join("shader.glsl")).unwrap();
        let manifest = ShaderBundleManifest {
            shader: "shader.glsl".to_string(),
            name: "Invalid Bundle".to_string(),
            author: "par-term".to_string(),
            description: "Shader path is a directory.".to_string(),
            license: "MIT".to_string(),
            textures: Vec::new(),
            cubemaps: Vec::new(),
            screenshot: None,
        };

        let err = manifest
            .validate_paths(temp.path())
            .expect_err("shader directory should fail validation");

        assert!(err.contains("shader"));
    }

    #[test]
    fn rejects_texture_path_that_is_a_directory() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::write(temp.path().join("shader.glsl"), "void mainImage(){}").unwrap();
        std::fs::create_dir_all(temp.path().join("textures/noise.png")).unwrap();
        let manifest = ShaderBundleManifest {
            shader: "shader.glsl".to_string(),
            name: "Invalid Bundle".to_string(),
            author: "par-term".to_string(),
            description: "Texture path is a directory.".to_string(),
            license: "MIT".to_string(),
            textures: vec!["textures/noise.png".to_string()],
            cubemaps: Vec::new(),
            screenshot: None,
        };

        let err = manifest
            .validate_paths(temp.path())
            .expect_err("texture directory should fail validation");

        assert!(err.contains("textures"));
    }

    #[test]
    fn rejects_screenshot_path_that_is_a_directory() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::write(temp.path().join("shader.glsl"), "void mainImage(){}").unwrap();
        std::fs::create_dir(temp.path().join("screenshot.png")).unwrap();
        let manifest = ShaderBundleManifest {
            shader: "shader.glsl".to_string(),
            name: "Invalid Bundle".to_string(),
            author: "par-term".to_string(),
            description: "Screenshot path is a directory.".to_string(),
            license: "MIT".to_string(),
            textures: Vec::new(),
            cubemaps: Vec::new(),
            screenshot: Some("screenshot.png".to_string()),
        };

        let err = manifest
            .validate_paths(temp.path())
            .expect_err("screenshot directory should fail validation");

        assert!(err.contains("screenshot"));
    }

    #[test]
    fn shader_bundle_shader_path_must_be_glsl() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::write(temp.path().join("shader.wgsl"), "// wrong extension").unwrap();
        let manifest = ShaderBundleManifest {
            shader: "shader.wgsl".to_string(),
            name: "Invalid Bundle".to_string(),
            author: "par-term".to_string(),
            description: "Invalid shader extension.".to_string(),
            license: "MIT".to_string(),
            textures: Vec::new(),
            cubemaps: Vec::new(),
            screenshot: None,
        };

        let err = manifest
            .validate_paths(temp.path())
            .expect_err("non-GLSL shader should fail");

        assert!(err.contains(".glsl"));
    }

    #[test]
    fn validates_cubemap_prefix_requires_all_six_faces() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::write(temp.path().join("shader.glsl"), "void mainImage(){}").unwrap();
        for suffix in ["px", "nx", "py", "ny", "pz"] {
            std::fs::write(temp.path().join(format!("env-{suffix}.png")), b"fake").unwrap();
        }
        let manifest = ShaderBundleManifest {
            shader: "shader.glsl".to_string(),
            name: "Cubemap Bundle".to_string(),
            author: "par-term".to_string(),
            description: "Cubemap validation test.".to_string(),
            license: "MIT".to_string(),
            textures: Vec::new(),
            cubemaps: vec!["env".to_string()],
            screenshot: None,
        };

        let err = manifest
            .validate_paths(temp.path())
            .expect_err("missing nz cubemap face should fail");

        assert!(err.contains("nz"));
    }

    #[test]
    fn rejects_cubemap_face_path_that_is_a_directory() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::write(temp.path().join("shader.glsl"), "void mainImage(){}").unwrap();
        for suffix in ["px", "nx", "py", "ny", "pz", "nz"] {
            std::fs::create_dir(temp.path().join(format!("env-{suffix}.png"))).unwrap();
        }
        let manifest = ShaderBundleManifest {
            shader: "shader.glsl".to_string(),
            name: "Cubemap Bundle".to_string(),
            author: "par-term".to_string(),
            description: "Cubemap validation test.".to_string(),
            license: "MIT".to_string(),
            textures: Vec::new(),
            cubemaps: vec!["env".to_string()],
            screenshot: None,
        };

        let err = manifest
            .validate_paths(temp.path())
            .expect_err("cubemap face directories should fail validation");

        assert!(err.contains("px"));
    }
}