Skip to main content

idlewarden_plugin_api/
value.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Dynamically-typed signal values.
3//!
4//! The Core must never know the shape of any particular game's state
5//! (ADR-0002). A plugin declares a *schema* of signals in its manifest; at
6//! runtime it emits [`Value`]s that the Core validates against that schema and
7//! that the UI renders generically.
8
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12#[serde(tag = "type", content = "value", rename_all = "snake_case")]
13pub enum Value {
14    Bool(bool),
15    Int(i64),
16    Float(f64),
17    /// A ratio in `0.0..=1.0`, e.g. a health or progress bar.
18    Ratio(f64),
19    Text(String),
20    /// A point in *window-relative* coordinates (ADR-0003): never screen pixels.
21    Point {
22        x: f64,
23        y: f64,
24    },
25    Rect {
26        x: f64,
27        y: f64,
28        w: f64,
29        h: f64,
30    },
31    /// An opaque identifier, e.g. the id of the UI screen currently shown.
32    Enum(String),
33}
34
35impl Value {
36    /// The name of the variant, used for schema validation error messages.
37    pub fn type_name(&self) -> &'static str {
38        match self {
39            Value::Bool(_) => "bool",
40            Value::Int(_) => "int",
41            Value::Float(_) => "float",
42            Value::Ratio(_) => "ratio",
43            Value::Text(_) => "text",
44            Value::Point { .. } => "point",
45            Value::Rect { .. } => "rect",
46            Value::Enum(_) => "enum",
47        }
48    }
49
50    /// `Ratio` values are the only ones with an enforced range.
51    pub fn is_well_formed(&self) -> bool {
52        match self {
53            Value::Ratio(r) => (0.0..=1.0).contains(r),
54            Value::Float(f) => f.is_finite(),
55            Value::Point { x, y } => x.is_finite() && y.is_finite(),
56            Value::Rect { x, y, w, h } => {
57                x.is_finite() && y.is_finite() && w.is_finite() && h.is_finite()
58            }
59            _ => true,
60        }
61    }
62}