Skip to main content

par_term_config/types/
shader.rs

1//! Shader configuration types: per-shader settings, metadata, and resolved configs.
2
3use serde::de::Error as DeError;
4use serde::ser::SerializeSeq;
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6use std::collections::BTreeMap;
7use std::path::PathBuf;
8
9// ============================================================================
10// Per-Shader Configuration Types
11// ============================================================================
12
13/// Metadata embedded in shader files via YAML block comments.
14///
15/// Parsed from `/*! par-term shader metadata ... */` blocks at the top of shader files.
16#[derive(Debug, Clone, Default, Serialize, Deserialize)]
17pub struct ShaderMetadata {
18    /// Human-readable name for the shader (e.g., "CRT Effect")
19    pub name: Option<String>,
20    /// Author of the shader
21    pub author: Option<String>,
22    /// Description of what the shader does
23    pub description: Option<String>,
24    /// Version string (e.g., "1.0.0")
25    pub version: Option<String>,
26    /// Default configuration values for this shader
27    #[serde(default)]
28    pub defaults: ShaderConfig,
29    /// Optional safety/readability badges shown in settings.
30    #[serde(default, skip_serializing_if = "Vec::is_empty")]
31    pub safety_badges: Vec<ShaderSafetyBadge>,
32}
33
34/// Readability/performance badges displayed for background shaders.
35/// Readability/performance badges displayed for background shaders.
36///
37/// These badges appear in the settings UI to indicate shader characteristics
38/// that affect text readability, GPU performance, or resource usage.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(rename_all = "snake_case")]
41pub enum ShaderSafetyBadge {
42    /// Shader processes full terminal content (higher GPU cost, may distort text).
43    FullContent,
44    /// Shader may distort or obscure text content.
45    DistortsText,
46    /// Shader loads external texture files via iChannel0-3.
47    UsesTextures,
48    /// Shader loads a cubemap texture for environment mapping.
49    UsesCubemap,
50    /// Shader has high GPU compute cost (may impact battery life).
51    HighGpuCost,
52    /// Shader is lightweight and works well on battery power.
53    BatteryFriendly,
54}
55
56impl ShaderSafetyBadge {
57    pub fn label(self) -> &'static str {
58        match self {
59            Self::FullContent => "full-content",
60            Self::DistortsText => "distorts text",
61            Self::UsesTextures => "uses textures",
62            Self::UsesCubemap => "uses cubemap",
63            Self::HighGpuCost => "high GPU cost",
64            Self::BatteryFriendly => "works well on battery",
65        }
66    }
67}
68
69/// Blend mode for compositing shader output over the background image.
70///
71/// Controls how the shader output is blended with the app's background image
72/// when `use_background_as_channel0` is enabled.
73#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
74#[serde(rename_all = "snake_case")]
75pub enum ShaderBackgroundBlendMode {
76    /// Replace the background entirely with shader output.
77    #[default]
78    Replace,
79    /// Multiply shader output with the background (darkens).
80    Multiply,
81    /// Screen blend (lightens, opposite of multiply).
82    Screen,
83    /// Overlay blend (combines multiply and screen based on brightness).
84    Overlay,
85    /// Use shader luminance as an alpha mask over the background.
86    LuminanceMask,
87}
88
89impl ShaderBackgroundBlendMode {
90    pub const ALL: [Self; 5] = [
91        Self::Replace,
92        Self::Multiply,
93        Self::Screen,
94        Self::Overlay,
95        Self::LuminanceMask,
96    ];
97
98    pub fn as_uniform_int(self) -> i32 {
99        match self {
100            Self::Replace => 0,
101            Self::Multiply => 1,
102            Self::Screen => 2,
103            Self::Overlay => 3,
104            Self::LuminanceMask => 4,
105        }
106    }
107
108    pub fn display_name(self) -> &'static str {
109        match self {
110            Self::Replace => "Replace",
111            Self::Multiply => "Multiply",
112            Self::Screen => "Screen",
113            Self::Overlay => "Overlay",
114            Self::LuminanceMask => "Luminance mask",
115        }
116    }
117}
118
119/// An RGBA color value stored as normalized floats (0.0-1.0 per channel).
120///
121/// Used for shader uniform color values. Parsed from hex strings (`#rrggbb`
122/// or `#rrggbbaa`) or from 3/4-element float arrays in YAML config.
123#[derive(Debug, Copy, Clone, PartialEq)]
124pub struct ShaderColorValue(pub [f32; 4]);
125
126impl ShaderColorValue {
127    fn from_hex(value: &str) -> Result<Self, String> {
128        let hex = value
129            .strip_prefix('#')
130            .ok_or_else(|| "color hex value must start with `#`".to_string())?;
131
132        // The ASCII check is what makes the byte ranges below valid slice
133        // bounds: a multi-byte character would otherwise split mid-character.
134        if !hex.is_ascii() || (hex.len() != 6 && hex.len() != 8) {
135            return Err("color hex value must be `#rrggbb` or `#rrggbbaa`".to_string());
136        }
137
138        let parse_channel = |range: std::ops::Range<usize>| -> Result<f32, String> {
139            u8::from_str_radix(&hex[range], 16)
140                .map(|value| f32::from(value) / 255.0)
141                .map_err(|_| "color hex value contains non-hex digits".to_string())
142        };
143
144        Ok(Self([
145            parse_channel(0..2)?,
146            parse_channel(2..4)?,
147            parse_channel(4..6)?,
148            if hex.len() == 8 {
149                parse_channel(6..8)?
150            } else {
151                1.0
152            },
153        ]))
154    }
155
156    fn from_components(components: &[serde_yaml_ng::Value]) -> Result<Self, String> {
157        if components.len() != 3 && components.len() != 4 {
158            return Err("color array must have 3 or 4 normalized float components".to_string());
159        }
160
161        let mut color = [1.0_f32; 4];
162        for (index, component) in components.iter().enumerate() {
163            let value = match component {
164                serde_yaml_ng::Value::Number(number) => number
165                    .as_f64()
166                    .ok_or_else(|| "color array component must be numeric".to_string())?,
167                _ => return Err("color array components must be numeric".to_string()),
168            };
169
170            if !value.is_finite() || !(0.0..=1.0).contains(&value) {
171                return Err(
172                    "color array components must be finite normalized values in 0.0..=1.0"
173                        .to_string(),
174                );
175            }
176
177            color[index] = value as f32;
178        }
179
180        Ok(Self(color))
181    }
182
183    fn to_hex_string(self) -> String {
184        let channels = self
185            .0
186            .map(|value| ((value.clamp(0.0, 1.0) * 255.0).round()) as u8);
187        if channels[3] == 255 {
188            format!("#{:02x}{:02x}{:02x}", channels[0], channels[1], channels[2])
189        } else {
190            format!(
191                "#{:02x}{:02x}{:02x}{:02x}",
192                channels[0], channels[1], channels[2], channels[3]
193            )
194        }
195    }
196}
197
198/// A typed value for a custom shader uniform.
199///
200/// Supports the GLSL types that can be declared as `// control` uniforms in
201/// shader files: float, int, bool, color (vec3/vec4), and vec2.
202#[derive(Debug, Clone, PartialEq)]
203pub enum ShaderUniformValue {
204    /// A single-precision floating-point value.
205    Float(f32),
206    /// A 32-bit integer value.
207    Int(i32),
208    /// A boolean value.
209    Bool(bool),
210    /// A color value (RGB or RGBA as normalized floats).
211    Color(ShaderColorValue),
212    /// A 2-component float vector.
213    Vec2([f32; 2]),
214}
215
216impl ShaderUniformValue {
217    fn numeric_component(component: &serde_yaml_ng::Value, context: &str) -> Result<f32, String> {
218        let value = match component {
219            serde_yaml_ng::Value::Number(number) => number
220                .as_f64()
221                .ok_or_else(|| format!("{} component must be numeric", context))?,
222            _ => return Err(format!("{} components must be numeric", context)),
223        };
224
225        if !value.is_finite() {
226            return Err(format!("{} components must be finite", context));
227        }
228
229        Ok(value as f32)
230    }
231
232    fn vec2_from_components(components: &[serde_yaml_ng::Value]) -> Result<[f32; 2], String> {
233        if components.len() != 2 {
234            return Err("vec2 array must have exactly 2 finite numeric components".to_string());
235        }
236
237        Ok([
238            Self::numeric_component(&components[0], "vec2 array")?,
239            Self::numeric_component(&components[1], "vec2 array")?,
240        ])
241    }
242
243    fn from_yaml_value(value: &serde_yaml_ng::Value) -> Result<Self, String> {
244        match value {
245            serde_yaml_ng::Value::Bool(value) => Ok(Self::Bool(*value)),
246            serde_yaml_ng::Value::Number(number) => {
247                let value = number
248                    .as_f64()
249                    .ok_or_else(|| "numeric uniform value must be numeric".to_string())?;
250                if !value.is_finite() {
251                    return Err("numeric uniform value must be finite".to_string());
252                }
253
254                if value.fract() == 0.0 {
255                    if value >= f64::from(i32::MIN) && value <= f64::from(i32::MAX) {
256                        Ok(Self::Int(value as i32))
257                    } else {
258                        Err("integer uniform value must fit i32".to_string())
259                    }
260                } else {
261                    Ok(Self::Float(value as f32))
262                }
263            }
264            serde_yaml_ng::Value::String(value) if value.starts_with('#') => {
265                ShaderColorValue::from_hex(value).map(Self::Color)
266            }
267            serde_yaml_ng::Value::String(_) => {
268                Err("string uniform values are only supported for color hex strings".to_string())
269            }
270            serde_yaml_ng::Value::Sequence(components) if components.len() == 2 => {
271                Self::vec2_from_components(components).map(Self::Vec2)
272            }
273            serde_yaml_ng::Value::Sequence(components)
274                if components.len() == 3 || components.len() == 4 =>
275            {
276                ShaderColorValue::from_components(components).map(Self::Color)
277            }
278            serde_yaml_ng::Value::Sequence(_) => {
279                Err("shader uniform arrays must have length 2 (vec2) or 3/4 (color)".to_string())
280            }
281            _ => Err("unsupported shader uniform value type".to_string()),
282        }
283    }
284}
285
286impl Serialize for ShaderUniformValue {
287    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
288    where
289        S: Serializer,
290    {
291        match self {
292            Self::Float(value) => serializer.serialize_f32(*value),
293            Self::Int(value) => serializer.serialize_i32(*value),
294            Self::Bool(value) => serializer.serialize_bool(*value),
295            Self::Color(value) => serializer.serialize_str(&value.to_hex_string()),
296            Self::Vec2(value) => {
297                let mut sequence = serializer.serialize_seq(Some(2))?;
298                sequence.serialize_element(&value[0])?;
299                sequence.serialize_element(&value[1])?;
300                sequence.end()
301            }
302        }
303    }
304}
305
306impl<'de> Deserialize<'de> for ShaderUniformValue {
307    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
308    where
309        D: Deserializer<'de>,
310    {
311        let value = serde_yaml_ng::Value::deserialize(deserializer)?;
312        Self::from_yaml_value(&value).map_err(D::Error::custom)
313    }
314}
315
316fn deserialize_uniforms<'de, D>(
317    deserializer: D,
318) -> Result<BTreeMap<String, ShaderUniformValue>, D::Error>
319where
320    D: Deserializer<'de>,
321{
322    let raw = BTreeMap::<String, serde_yaml_ng::Value>::deserialize(deserializer)?;
323    let mut uniforms = BTreeMap::new();
324
325    for (name, value) in raw {
326        match ShaderUniformValue::from_yaml_value(&value) {
327            Ok(value) => {
328                uniforms.insert(name, value);
329            }
330            Err(error) => {
331                log::warn!(
332                    "Skipping invalid shader uniform default `{}`: {}",
333                    name,
334                    error
335                );
336            }
337        }
338    }
339
340    Ok(uniforms)
341}
342
343/// Per-shader configuration settings.
344///
345/// Used both for embedded defaults in shader files and for user overrides in config.yaml.
346/// All fields are optional to allow partial overrides.
347#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
348pub struct ShaderConfig {
349    /// Animation speed multiplier (1.0 = normal speed)
350    pub animation_speed: Option<f32>,
351    /// Brightness multiplier (0.05-1.0)
352    pub brightness: Option<f32>,
353    /// Text opacity when using this shader (0.0-1.0)
354    pub text_opacity: Option<f32>,
355    /// When true, shader receives full terminal content for manipulation
356    pub full_content: Option<bool>,
357    /// Path to texture for iChannel0
358    pub channel0: Option<String>,
359    /// Path to texture for iChannel1
360    pub channel1: Option<String>,
361    /// Path to texture for iChannel2
362    pub channel2: Option<String>,
363    /// Path to texture for iChannel3
364    pub channel3: Option<String>,
365    /// Path prefix for cubemap faces
366    pub cubemap: Option<String>,
367    /// Whether cubemap sampling is enabled
368    pub cubemap_enabled: Option<bool>,
369    /// Use the app's background image as iChannel0 instead of a separate texture
370    pub use_background_as_channel0: Option<bool>,
371    /// Blend mode hint for shaders using the app background as iChannel0.
372    pub background_channel0_blend_mode: Option<ShaderBackgroundBlendMode>,
373    /// Auto-dim shader output beneath terminal text/content for readability.
374    pub auto_dim_under_text: Option<bool>,
375    /// Strength of auto-dimming under text (0.0 = no extra dimming, 1.0 = black).
376    pub auto_dim_strength: Option<f32>,
377    /// Custom shader uniform values for `// control ...` declarations.
378    #[serde(
379        default,
380        deserialize_with = "deserialize_uniforms",
381        skip_serializing_if = "BTreeMap::is_empty"
382    )]
383    pub uniforms: BTreeMap<String, ShaderUniformValue>,
384}
385
386/// Cursor shader specific configuration.
387///
388/// Extends base ShaderConfig with cursor-specific settings.
389#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
390pub struct CursorShaderConfig {
391    /// Base shader configuration
392    #[serde(flatten)]
393    pub base: ShaderConfig,
394    /// Hide the default cursor when this shader is enabled
395    pub hides_cursor: Option<bool>,
396    /// Disable cursor shader while in alt screen (vim, less, htop)
397    pub disable_in_alt_screen: Option<bool>,
398    /// Cursor glow radius in pixels
399    pub glow_radius: Option<f32>,
400    /// Cursor glow intensity (0.0-1.0)
401    pub glow_intensity: Option<f32>,
402    /// Duration of cursor trail effect in seconds
403    pub trail_duration: Option<f32>,
404    /// Cursor color for shader effects [R, G, B] (0-255)
405    pub cursor_color: Option<[u8; 3]>,
406}
407
408/// Metadata embedded in cursor shader files via YAML block comments.
409///
410/// Parsed from `/*! par-term shader metadata ... */` blocks at the top of cursor shader files.
411/// Similar to `ShaderMetadata` but with cursor-specific defaults.
412#[derive(Debug, Clone, Default, Serialize, Deserialize)]
413pub struct CursorShaderMetadata {
414    /// Human-readable name for the shader (e.g., "Cursor Glow Effect")
415    pub name: Option<String>,
416    /// Author of the shader
417    pub author: Option<String>,
418    /// Description of what the shader does
419    pub description: Option<String>,
420    /// Version string (e.g., "1.0.0")
421    pub version: Option<String>,
422    /// Default configuration values for this cursor shader
423    #[serde(default)]
424    pub defaults: CursorShaderConfig,
425}
426
427/// Fully resolved shader configuration with all values filled in.
428///
429/// Created by merging user overrides, shader metadata defaults, and global defaults.
430#[derive(Debug, Clone)]
431pub struct ResolvedShaderConfig {
432    /// Animation speed multiplier
433    pub animation_speed: f32,
434    /// Brightness multiplier
435    pub brightness: f32,
436    /// Text opacity
437    pub text_opacity: f32,
438    /// Full content mode enabled
439    pub full_content: bool,
440    /// Resolved path to iChannel0 texture
441    pub channel0: Option<PathBuf>,
442    /// Resolved path to iChannel1 texture
443    pub channel1: Option<PathBuf>,
444    /// Resolved path to iChannel2 texture
445    pub channel2: Option<PathBuf>,
446    /// Resolved path to iChannel3 texture
447    pub channel3: Option<PathBuf>,
448    /// Resolved cubemap path prefix
449    pub cubemap: Option<PathBuf>,
450    /// Cubemap sampling enabled
451    pub cubemap_enabled: bool,
452    /// Use the app's background image as iChannel0
453    pub use_background_as_channel0: bool,
454    /// Blend mode hint for shaders using the app background as iChannel0.
455    pub background_channel0_blend_mode: ShaderBackgroundBlendMode,
456    /// Auto-dim shader output beneath terminal text/content for readability.
457    pub auto_dim_under_text: bool,
458    /// Strength of auto-dimming under text.
459    pub auto_dim_strength: f32,
460    /// Custom shader uniform values resolved from metadata defaults and user overrides.
461    pub custom_uniforms: BTreeMap<String, ShaderUniformValue>,
462}
463
464impl Default for ResolvedShaderConfig {
465    fn default() -> Self {
466        Self {
467            animation_speed: 1.0,
468            brightness: 1.0,
469            text_opacity: 1.0,
470            full_content: false,
471            channel0: None,
472            channel1: None,
473            channel2: None,
474            channel3: None,
475            cubemap: None,
476            cubemap_enabled: true,
477            use_background_as_channel0: false,
478            background_channel0_blend_mode: ShaderBackgroundBlendMode::Replace,
479            auto_dim_under_text: false,
480            auto_dim_strength: 0.35,
481            custom_uniforms: BTreeMap::new(),
482        }
483    }
484}
485
486/// Fully resolved cursor shader configuration with all values filled in.
487#[derive(Debug, Clone)]
488pub struct ResolvedCursorShaderConfig {
489    /// Base resolved shader config
490    pub base: ResolvedShaderConfig,
491    /// Hide the default cursor when this shader is enabled
492    pub hides_cursor: bool,
493    /// Disable cursor shader while in alt screen (vim, less, htop)
494    pub disable_in_alt_screen: bool,
495    /// Cursor glow radius in pixels
496    pub glow_radius: f32,
497    /// Cursor glow intensity (0.0-1.0)
498    pub glow_intensity: f32,
499    /// Duration of cursor trail effect in seconds
500    pub trail_duration: f32,
501    /// Cursor color for shader effects [R, G, B] (0-255)
502    pub cursor_color: [u8; 3],
503}
504
505impl Default for ResolvedCursorShaderConfig {
506    fn default() -> Self {
507        Self {
508            base: ResolvedShaderConfig::default(),
509            hides_cursor: false,
510            disable_in_alt_screen: true,
511            glow_radius: 80.0,
512            glow_intensity: 0.3,
513            trail_duration: 0.5,
514            cursor_color: [255, 255, 255],
515        }
516    }
517}
518
519#[cfg(test)]
520mod tests {
521    use super::*;
522
523    #[test]
524    fn color_from_hex_rejects_non_ascii_without_panicking() {
525        // Six bytes, four characters — the old byte-length gate accepted these
526        // and then split `é` down the middle.
527        assert!(ShaderColorValue::from_hex("#1é234").is_err());
528        assert!(ShaderColorValue::from_hex("#café12").is_err());
529        assert!(ShaderColorValue::from_hex("#日本").is_err());
530        assert!(ShaderColorValue::from_hex("#😀😀").is_err());
531    }
532
533    #[test]
534    fn color_from_hex_still_accepts_ascii_forms() {
535        assert_eq!(
536            ShaderColorValue::from_hex("#ff8000").expect("rrggbb parses"),
537            ShaderColorValue([1.0, 128.0 / 255.0, 0.0, 1.0])
538        );
539        assert_eq!(
540            ShaderColorValue::from_hex("#00000080").expect("rrggbbaa parses"),
541            ShaderColorValue([0.0, 0.0, 0.0, 128.0 / 255.0])
542        );
543        assert!(ShaderColorValue::from_hex("#gg0000").is_err());
544    }
545
546    #[test]
547    fn non_ascii_color_uniform_is_skipped_not_fatal() {
548        let yaml = "uniforms:\n  iTint: \"#1é234\"\n";
549        let config: ShaderConfig =
550            serde_yaml_ng::from_str(yaml).expect("deserialize shader config");
551        assert!(!config.uniforms.contains_key("iTint"));
552    }
553
554    #[test]
555    fn shader_uniform_values_parse_int_float_and_vec2_defaults() {
556        let yaml = r#"
557uniforms:
558  iCount: 4
559  iGlow: 0.75
560  iOrigin: [0.25, 0.5]
561  iTint: [1.0, 0.5, 0.0]
562  iEnabled: true
563  iBadVec2: [0.0, .inf]
564  iBadString: not-a-color
565"#;
566
567        let config: ShaderConfig =
568            serde_yaml_ng::from_str(yaml).expect("deserialize shader config");
569
570        assert_eq!(
571            config.uniforms.get("iCount"),
572            Some(&ShaderUniformValue::Int(4))
573        );
574        assert_eq!(
575            config.uniforms.get("iGlow"),
576            Some(&ShaderUniformValue::Float(0.75))
577        );
578        assert_eq!(
579            config.uniforms.get("iOrigin"),
580            Some(&ShaderUniformValue::Vec2([0.25, 0.5]))
581        );
582        assert_eq!(
583            config.uniforms.get("iTint"),
584            Some(&ShaderUniformValue::Color(ShaderColorValue([
585                1.0, 0.5, 0.0, 1.0,
586            ])))
587        );
588        assert_eq!(
589            config.uniforms.get("iEnabled"),
590            Some(&ShaderUniformValue::Bool(true))
591        );
592        assert!(!config.uniforms.contains_key("iBadVec2"));
593        assert!(!config.uniforms.contains_key("iBadString"));
594
595        let serialized = serde_yaml_ng::to_string(&config).expect("serialize shader config");
596        assert!(serialized.contains("iCount: 4"));
597        assert!(serialized.contains("iOrigin:\n"));
598        assert!(serialized.contains("- 0.25"));
599        assert!(serialized.contains("- 0.5"));
600    }
601}