Skip to main content

ezu_graph/
registry.rs

1//! Node registry — maps op names to factory functions.
2//!
3//! The style parser (`ezu-style`) produces a [`spec::Document`] whose
4//! nodes carry an `op: String` and an opaque map of fields. The registry
5//! turns those entries into typed [`Node`] instances plus the list of
6//! input ports to wire up.
7//!
8//! Node implementations live in `ezu-paint` (and any downstream crate);
9//! they register themselves with a [`NodeRegistry`] which the application
10//! hands to [`build_graph`](crate::build_graph).
11
12use std::collections::HashMap;
13
14use ezu_style as spec;
15
16use crate::node::Node;
17
18/// One input port that a node wants connected, recorded by name.
19#[derive(Debug, Clone)]
20pub struct Connection {
21    /// Name of the input port on the node being built.
22    pub port: String,
23    /// Referenced node id (without the `@` prefix).
24    pub src: String,
25}
26
27/// What a [`NodeFactory`] returns: the constructed node plus its
28/// requested input wiring. The graph builder applies the connections
29/// after every node has been constructed.
30pub struct BuiltNode {
31    pub node: Box<dyn Node>,
32    pub connections: Vec<Connection>,
33}
34
35/// Read-only context handed to factories: lets them resolve `$param`
36/// and source references during construction.
37pub struct FactoryCtx<'a> {
38    pub params: &'a indexmap::IndexMap<String, spec::ParamDecl>,
39    pub sources: &'a indexmap::IndexMap<String, spec::SourceDecl>,
40}
41
42#[derive(Debug, thiserror::Error)]
43pub enum FactoryError {
44    #[error("missing required field `{0}`")]
45    MissingField(String),
46    #[error("field `{field}` has wrong type: {msg}")]
47    BadField { field: String, msg: String },
48    #[error("unknown param reference `${0}`")]
49    UnknownParam(String),
50    #[error("unknown asset reference `@{0}`")]
51    UnknownAsset(String),
52    #[error("{0}")]
53    Custom(String),
54}
55
56/// Trait every op implementation provides one of.
57///
58/// Factories are typically zero-sized structs. They inspect the JSON
59/// `fields` map, validate types, and return a [`BuiltNode`]. They MUST
60/// NOT execute any rendering — only construction.
61pub trait NodeFactory: Send + Sync {
62    /// Op name used as the registry key (e.g. `"solid"`, `"fill-solid"`).
63    fn op_name(&self) -> &'static str;
64
65    fn build(
66        &self,
67        fields: &serde_json::Map<String, serde_json::Value>,
68        ctx: &FactoryCtx<'_>,
69    ) -> Result<BuiltNode, FactoryError>;
70
71    /// JSON Schema fragment describing this op's field shape. Should
72    /// return a JSON object with `properties` and (optionally)
73    /// `required` keys — the `op` const is added by the registry.
74    ///
75    /// The default is permissive (any fields allowed). Override to opt
76    /// in to editor autocomplete and client-side validation.
77    fn schema(&self) -> serde_json::Value {
78        serde_json::json!({})
79    }
80}
81
82/// A factory submitted statically via [`inventory::submit!`]. Built-in
83/// node crates use this to self-register without touching a central
84/// list — see [`NodeRegistry::from_inventory`].
85pub struct StaticOp(pub &'static dyn NodeFactory);
86
87inventory::collect!(StaticOp);
88
89/// Submit a unit-struct [`NodeFactory`] to the global inventory so
90/// [`NodeRegistry::from_inventory`] picks it up.
91///
92/// ```ignore
93/// pub(super) struct SolidFactory;
94/// impl NodeFactory for SolidFactory { /* ... */ }
95/// ezu_graph::submit_node!(SolidFactory);
96/// ```
97#[macro_export]
98macro_rules! submit_node {
99    ($factory:ident) => {
100        $crate::inventory::submit! {
101            $crate::StaticOp(&$factory)
102        }
103    };
104}
105
106/// Catalog of registered ops, keyed by op name.
107#[derive(Default)]
108pub struct NodeRegistry {
109    ops: HashMap<&'static str, &'static dyn NodeFactory>,
110}
111
112impl NodeRegistry {
113    pub fn new() -> Self {
114        Self::default()
115    }
116
117    /// Build a registry from every [`StaticOp`] submitted via
118    /// [`inventory::submit!`] across the linked binary.
119    pub fn from_inventory() -> Self {
120        let mut r = Self::default();
121        for StaticOp(f) in inventory::iter::<StaticOp> {
122            r.register_static(*f);
123        }
124        r
125    }
126
127    /// Register a factory by leaking it into `'static`. Convenient for
128    /// dynamic registration; built-in ops should prefer
129    /// [`inventory::submit!`] + [`Self::from_inventory`].
130    pub fn register(&mut self, factory: impl NodeFactory + 'static) {
131        self.register_static(Box::leak(Box::new(factory)));
132    }
133
134    /// Register a `'static` factory reference (the form produced by
135    /// [`inventory::submit!`]).
136    pub fn register_static(&mut self, factory: &'static dyn NodeFactory) {
137        self.ops.insert(factory.op_name(), factory);
138    }
139
140    pub fn get(&self, op_name: &str) -> Option<&dyn NodeFactory> {
141        self.ops.get(op_name).copied()
142    }
143
144    /// All registered op names, sorted for deterministic output.
145    pub fn op_names(&self) -> Vec<&'static str> {
146        let mut names: Vec<_> = self.ops.keys().copied().collect();
147        names.sort_unstable();
148        names
149    }
150
151    /// Build a JSON Schema for a complete style document by gathering
152    /// each registered op's [`NodeFactory::schema`] under a `oneOf`. The
153    /// returned value is suitable for serving at
154    /// `/schemas/ezu-style.json` and feeding to editor tooling
155    /// (Monaco, vscode-json-languageservice, ajv, …).
156    pub fn document_schema(&self) -> serde_json::Value {
157        use serde_json::{json, Value};
158        let mut variants: Vec<Value> = Vec::with_capacity(self.ops.len());
159        for op in self.op_names() {
160            let factory = self
161                .ops
162                .get(op)
163                .expect("op_names yields keys present in self.ops");
164            let mut schema = factory.schema();
165            if !schema.is_object() {
166                schema = json!({});
167            }
168            let obj = schema
169                .as_object_mut()
170                .expect("schema was just normalized to an object");
171            obj.entry("type").or_insert_with(|| json!("object"));
172            // Add the discriminator field.
173            let props = obj
174                .entry("properties")
175                .or_insert_with(|| json!({}))
176                .as_object_mut()
177                .expect("`properties` was just inserted as a JSON object");
178            props.insert(
179                "op".to_string(),
180                json!({ "const": op, "description": format!("Selects the `{op}` operation.") }),
181            );
182            // Require `op`, preserving any other required fields.
183            let required = obj
184                .entry("required")
185                .or_insert_with(|| json!([]))
186                .as_array_mut()
187                .expect("`required` was just inserted as a JSON array");
188            if !required.iter().any(|v| v.as_str() == Some("op")) {
189                required.insert(0, json!("op"));
190            }
191            obj.insert("title".to_string(), json!(format!("op: {op}")));
192            variants.push(schema);
193        }
194
195        // Call into a user-defined function from the document's
196        // `functions` block. Arguments are function-specific, so the
197        // variant stays open beyond `op` / `fn`.
198        variants.push(json!({
199            "type": "object",
200            "title": "op: func",
201            "description": "Call a user-defined function declared in the document's `functions` block.",
202            "required": ["op", "fn"],
203            "properties": {
204                "op": { "const": "func" },
205                "fn": { "type": "string", "description": "Name of the function to call." }
206            },
207            "additionalProperties": true
208        }));
209
210        let func_kinds = json!([
211            "features",
212            "raster",
213            "sprite",
214            "brush",
215            "scalar",
216            "scalar-field"
217        ]);
218
219        json!({
220            "$schema": "https://json-schema.org/draft/2020-12/schema",
221            "title": "Ezu Style Spec",
222            "type": "object",
223            "required": ["name", "nodes", "output"],
224            "properties": {
225                "name": { "type": "string" },
226                "version": { "type": "string" },
227                "tile-size": { "type": "integer", "minimum": 1 },
228                "pad": { "type": "integer", "minimum": 0 },
229                "attribution": {
230                    "type": "string",
231                    "description": "Attribution for the style itself (HTML allowed). Merged with per-source and upstream attributions."
232                },
233                "params": {
234                    "type": "object",
235                    "additionalProperties": {
236                        "type": "object",
237                        "required": ["type", "default"],
238                        "properties": {
239                            "type": { "enum": ["color", "number", "bool"] },
240                            "default": {},
241                            "min": { "type": "number" },
242                            "max": { "type": "number" },
243                            "description": { "type": "string" }
244                        }
245                    }
246                },
247                "functions": {
248                    "type": "object",
249                    "description": "User-defined functions: reusable node subgraphs called via `op: func`.",
250                    "additionalProperties": {
251                        "type": "object",
252                        "required": ["output", "output-kind", "nodes"],
253                        "properties": {
254                            "description": { "type": "string" },
255                            "inputs": {
256                                "type": "object",
257                                "additionalProperties": {
258                                    "type": "object",
259                                    "required": ["kind"],
260                                    "properties": {
261                                        "kind": { "enum": func_kinds.clone() },
262                                        "default": {},
263                                        "description": { "type": "string" }
264                                    }
265                                }
266                            },
267                            "output": {
268                                "type": "string",
269                                "description": "Body node (with or without `@`) the call produces."
270                            },
271                            "output-kind": { "enum": func_kinds },
272                            "nodes": { "$ref": "#/properties/nodes" }
273                        }
274                    }
275                },
276                "sources": {
277                    "type": "object",
278                    "additionalProperties": {
279                        "oneOf": [
280                            {
281                                "type": "object",
282                                "required": ["type", "src"],
283                                "properties": {
284                                    "type": { "enum": ["brush", "image"] },
285                                    "src": { "type": "string" },
286                                    "attribution": { "type": "string" }
287                                }
288                            },
289                            {
290                                "type": "object",
291                                "required": ["type", "url"],
292                                "properties": {
293                                    "type": { "enum": ["mvt", "pmtiles"] },
294                                    "url": { "type": "string" },
295                                    "attribution": { "type": "string", "description": "Explicit attribution; inherits upstream TileJSON / PMTiles metadata when absent." }
296                                }
297                            },
298                            {
299                                "type": "object",
300                                "required": ["type", "url", "encoding"],
301                                "properties": {
302                                    "type": { "const": "dem" },
303                                    "url": { "type": "string", "description": "XYZ template or TileJSON URL." },
304                                    "encoding": { "enum": ["terrarium", "mapbox-rgb"] },
305                                    "tile-size": { "type": "integer", "minimum": 1 },
306                                    "max-zoom": { "type": "integer", "minimum": 0 },
307                                    "neighbor-fetch": { "type": "boolean" },
308                                    "elevation-offset": { "type": "number" },
309                                    "on-missing": { "enum": ["empty", "upsample", "error"], "default": "empty", "description": "404 within zoom range: zero elevation, upsample a parent, or fail the tile." },
310                                    "attribution": { "type": "string" }
311                                }
312                            },
313                            {
314                                "type": "object",
315                                "required": ["type", "url"],
316                                "properties": {
317                                    "type": { "const": "raster" },
318                                    "url": { "type": "string", "description": "XYZ template, TileJSON URL, or PMTiles archive (`.pmtiles`). PNG/WebP/JPEG tiles." },
319                                    "max-zoom": { "type": "integer", "minimum": 0 },
320                                    "neighbor-fetch": { "type": "boolean" },
321                                    "on-missing": { "enum": ["empty", "upsample", "error"], "default": "empty", "description": "404 within zoom range: transparent pixels, upsample a parent, or fail the tile." },
322                                    "attribution": { "type": "string" }
323                                }
324                            }
325                        ]
326                    }
327                },
328                "nodes": {
329                    "type": "object",
330                    "additionalProperties": { "oneOf": variants }
331                },
332                "output": {
333                    "type": "string",
334                    "description": "Node id of the final raster (with or without `@`)."
335                }
336            }
337        })
338    }
339}
340
341/// Pre-built JSON Schema fragments commonly reused by `NodeFactory::schema`
342/// implementations.
343pub mod schema_frag {
344    use serde_json::{json, Value};
345
346    /// A reference to another node, written `@id`.
347    pub fn node_ref() -> Value {
348        json!({
349            "type": "string",
350            "pattern": "^@?[A-Za-z_][A-Za-z0-9_-]*$",
351            "description": "Reference to another node (`@name`)."
352        })
353    }
354
355    /// A reference to a registered asset (brush / image / etc.).
356    pub fn asset_ref() -> Value {
357        json!({
358            "type": "string",
359            "description": "Asset reference (`@name`) or literal path."
360        })
361    }
362
363    /// `#rrggbb` or `#rrggbbaa` color literal. Also allows `$param`
364    /// and `@node` (scalar port).
365    pub fn color() -> Value {
366        json!({
367            "type": "string",
368            "pattern": "^(#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?|[$@][A-Za-z_][A-Za-z0-9_-]*)$",
369            "description": "sRGB hex color, `$param` reference, or `@node` scalar port."
370        })
371    }
372
373    /// Number in `[0, 1]` — commonly opacity / fraction parameters.
374    pub fn unit_number() -> Value {
375        in_number(json!({ "type": "number", "minimum": 0.0, "maximum": 1.0 }))
376    }
377
378    /// Non-negative number in pixels.
379    pub fn px_number() -> Value {
380        in_number(json!({ "type": "number", "minimum": 0.0 }))
381    }
382
383    /// Unconstrained number field.
384    pub fn number() -> Value {
385        in_number(json!({ "type": "number" }))
386    }
387
388    /// Wrap a numeric schema so the field also accepts `$param` /
389    /// `@node` reference strings (an [`In<f64>`](crate::input::In)
390    /// field).
391    pub fn in_number(literal: Value) -> Value {
392        json!({
393            "oneOf": [
394                literal,
395                {
396                    "type": "string",
397                    "pattern": "^[$@][A-Za-z_][A-Za-z0-9_-]*$",
398                    "description": "`$param` reference or `@node` scalar port."
399                }
400            ]
401        })
402    }
403}
404
405/// Helper for factory authors: extract a `@node-ref` from a string field.
406///
407/// Returns the bare node id (no `@`). Errors if the field is missing,
408/// not a string, or not a node reference.
409pub fn take_input_ref(
410    fields: &serde_json::Map<String, serde_json::Value>,
411    name: &str,
412) -> Result<String, FactoryError> {
413    let v = fields
414        .get(name)
415        .ok_or_else(|| FactoryError::MissingField(name.to_string()))?;
416    let s = v.as_str().ok_or_else(|| FactoryError::BadField {
417        field: name.to_string(),
418        msg: "expected string node reference".into(),
419    })?;
420    match spec::FieldRef::classify(s) {
421        spec::FieldRef::Node(id) => Ok(id.to_string()),
422        _ => Err(FactoryError::BadField {
423            field: name.to_string(),
424            msg: format!("expected `@node-ref`, got `{s}`"),
425        }),
426    }
427}
428
429/// Like [`take_input_ref`] but returns `None` if the field is absent
430/// or JSON `null`. Use for optional input ports.
431pub fn take_optional_input_ref(
432    fields: &serde_json::Map<String, serde_json::Value>,
433    name: &str,
434) -> Result<Option<String>, FactoryError> {
435    match fields.get(name) {
436        None => Ok(None),
437        Some(v) if v.is_null() => Ok(None),
438        Some(_) => Ok(Some(take_input_ref(fields, name)?)),
439    }
440}