Skip to main content

sim_lib_intent/
citizen.rs

1use sim_citizen_derive::Citizen;
2use sim_kernel::{Expr, Result, Symbol};
3
4use crate::{Origin, intent};
5
6/// A validated Intent wrapped as a runtime Citizen object.
7#[derive(Clone, Debug, PartialEq, Citizen)]
8#[citizen(symbol = "intent/Intent", version = 1)]
9pub struct IntentDescriptor {
10    #[citizen(with = "intent_expr")]
11    intent: Expr,
12}
13
14impl IntentDescriptor {
15    /// Builds a descriptor from an Intent expression, validating it.
16    ///
17    /// # Errors
18    ///
19    /// Returns an error when `intent` is not a well-formed Intent expression.
20    pub fn from_expr(intent: Expr) -> Result<Self> {
21        intent_expr::decode(&intent)?;
22        Ok(Self { intent })
23    }
24
25    /// Returns the underlying Intent expression.
26    pub fn as_expr(&self) -> &Expr {
27        &self.intent
28    }
29}
30
31impl Default for IntentDescriptor {
32    fn default() -> Self {
33        Self::from_expr(intent(
34            "set-lens",
35            Origin::human(1),
36            vec![
37                ("pane", Expr::Symbol(Symbol::new("pane-1"))),
38                ("lens", Expr::Symbol(Symbol::new("view:default"))),
39            ],
40        ))
41        .expect("default intent descriptor should be valid")
42    }
43}
44
45/// Returns the class symbol for the Intent descriptor Citizen.
46pub fn intent_descriptor_class_symbol() -> Symbol {
47    Symbol::qualified("intent", "Intent")
48}
49
50pub(crate) mod intent_expr {
51    use sim_kernel::{Error, Expr, Result};
52
53    use crate::validate_intent;
54
55    pub fn encode(expr: &Expr) -> Expr {
56        expr.clone()
57    }
58
59    pub fn decode(expr: &Expr) -> Result<Expr> {
60        validate_intent(expr).map_err(|error| Error::Eval(format!("malformed intent: {error}")))?;
61        Ok(expr.clone())
62    }
63}