ezu-graph 0.4.2

Typed DAG evaluator for the Ezu Style Spec
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Node registry — maps op names to factory functions.
//!
//! The style parser (`ezu-style`) produces a [`spec::Document`] whose
//! nodes carry an `op: String` and an opaque map of fields. The registry
//! turns those entries into typed [`Node`] instances plus the list of
//! input ports to wire up.
//!
//! Node implementations live in `ezu-paint` (and any downstream crate);
//! they register themselves with a [`NodeRegistry`] which the application
//! hands to [`build_graph`](crate::build_graph).

use std::collections::HashMap;

use ezu_style as spec;

use crate::node::Node;

/// One input port that a node wants connected, recorded by name.
#[derive(Debug, Clone)]
pub struct Connection {
    /// Name of the input port on the node being built.
    pub port: String,
    /// Referenced node id (without the `@` prefix).
    pub src: String,
}

/// What a [`NodeFactory`] returns: the constructed node plus its
/// requested input wiring. The graph builder applies the connections
/// after every node has been constructed.
pub struct BuiltNode {
    pub node: Box<dyn Node>,
    pub connections: Vec<Connection>,
}

/// Read-only context handed to factories: lets them resolve `$param`
/// and source references during construction.
pub struct FactoryCtx<'a> {
    pub params: &'a indexmap::IndexMap<String, spec::ParamDecl>,
    pub sources: &'a indexmap::IndexMap<String, spec::SourceDecl>,
}

#[derive(Debug, thiserror::Error)]
pub enum FactoryError {
    #[error("missing required field `{0}`")]
    MissingField(String),
    #[error("field `{field}` has wrong type: {msg}")]
    BadField { field: String, msg: String },
    #[error("unknown param reference `${0}`")]
    UnknownParam(String),
    #[error("unknown asset reference `@{0}`")]
    UnknownAsset(String),
    #[error("{0}")]
    Custom(String),
}

/// Trait every op implementation provides one of.
///
/// Factories are typically zero-sized structs. They inspect the JSON
/// `fields` map, validate types, and return a [`BuiltNode`]. They MUST
/// NOT execute any rendering — only construction.
pub trait NodeFactory: Send + Sync {
    /// Op name used as the registry key (e.g. `"solid"`, `"fill-solid"`).
    fn op_name(&self) -> &'static str;

    fn build(
        &self,
        fields: &serde_json::Map<String, serde_json::Value>,
        ctx: &FactoryCtx<'_>,
    ) -> Result<BuiltNode, FactoryError>;

    /// JSON Schema fragment describing this op's field shape. Should
    /// return a JSON object with `properties` and (optionally)
    /// `required` keys — the `op` const is added by the registry.
    ///
    /// The default is permissive (any fields allowed). Override to opt
    /// in to editor autocomplete and client-side validation.
    fn schema(&self) -> serde_json::Value {
        serde_json::json!({})
    }
}

/// A factory submitted statically via [`inventory::submit!`]. Built-in
/// node crates use this to self-register without touching a central
/// list — see [`NodeRegistry::from_inventory`].
pub struct StaticOp(pub &'static dyn NodeFactory);

inventory::collect!(StaticOp);

/// Submit a unit-struct [`NodeFactory`] to the global inventory so
/// [`NodeRegistry::from_inventory`] picks it up.
///
/// ```ignore
/// pub(super) struct SolidFactory;
/// impl NodeFactory for SolidFactory { /* ... */ }
/// ezu_graph::submit_node!(SolidFactory);
/// ```
#[macro_export]
macro_rules! submit_node {
    ($factory:ident) => {
        $crate::inventory::submit! {
            $crate::StaticOp(&$factory)
        }
    };
}

/// Catalog of registered ops, keyed by op name.
#[derive(Default)]
pub struct NodeRegistry {
    ops: HashMap<&'static str, &'static dyn NodeFactory>,
}

impl NodeRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    /// Build a registry from every [`StaticOp`] submitted via
    /// [`inventory::submit!`] across the linked binary.
    pub fn from_inventory() -> Self {
        let mut r = Self::default();
        for StaticOp(f) in inventory::iter::<StaticOp> {
            r.register_static(*f);
        }
        r
    }

    /// Register a factory by leaking it into `'static`. Convenient for
    /// dynamic registration; built-in ops should prefer
    /// [`inventory::submit!`] + [`Self::from_inventory`].
    pub fn register(&mut self, factory: impl NodeFactory + 'static) {
        self.register_static(Box::leak(Box::new(factory)));
    }

    /// Register a `'static` factory reference (the form produced by
    /// [`inventory::submit!`]).
    pub fn register_static(&mut self, factory: &'static dyn NodeFactory) {
        self.ops.insert(factory.op_name(), factory);
    }

    pub fn get(&self, op_name: &str) -> Option<&dyn NodeFactory> {
        self.ops.get(op_name).copied()
    }

    /// All registered op names, sorted for deterministic output.
    pub fn op_names(&self) -> Vec<&'static str> {
        let mut names: Vec<_> = self.ops.keys().copied().collect();
        names.sort_unstable();
        names
    }

    /// Build a JSON Schema for a complete style document by gathering
    /// each registered op's [`NodeFactory::schema`] under a `oneOf`. The
    /// returned value is suitable for serving at
    /// `/schemas/ezu-style.json` and feeding to editor tooling
    /// (Monaco, vscode-json-languageservice, ajv, …).
    pub fn document_schema(&self) -> serde_json::Value {
        use serde_json::{json, Value};
        let mut variants: Vec<Value> = Vec::with_capacity(self.ops.len());
        for op in self.op_names() {
            let factory = self
                .ops
                .get(op)
                .expect("op_names yields keys present in self.ops");
            let mut schema = factory.schema();
            if !schema.is_object() {
                schema = json!({});
            }
            let obj = schema
                .as_object_mut()
                .expect("schema was just normalized to an object");
            obj.entry("type").or_insert_with(|| json!("object"));
            // Add the discriminator field.
            let props = obj
                .entry("properties")
                .or_insert_with(|| json!({}))
                .as_object_mut()
                .expect("`properties` was just inserted as a JSON object");
            props.insert(
                "op".to_string(),
                json!({ "const": op, "description": format!("Selects the `{op}` operation.") }),
            );
            // Require `op`, preserving any other required fields.
            let required = obj
                .entry("required")
                .or_insert_with(|| json!([]))
                .as_array_mut()
                .expect("`required` was just inserted as a JSON array");
            if !required.iter().any(|v| v.as_str() == Some("op")) {
                required.insert(0, json!("op"));
            }
            obj.insert("title".to_string(), json!(format!("op: {op}")));
            variants.push(schema);
        }

        // Call into a user-defined function from the document's
        // `functions` block. Arguments are function-specific, so the
        // variant stays open beyond `op` / `fn`.
        variants.push(json!({
            "type": "object",
            "title": "op: func",
            "description": "Call a user-defined function declared in the document's `functions` block.",
            "required": ["op", "fn"],
            "properties": {
                "op": { "const": "func" },
                "fn": { "type": "string", "description": "Name of the function to call." }
            },
            "additionalProperties": true
        }));

        let func_kinds = json!([
            "features",
            "raster",
            "sprite",
            "brush",
            "scalar",
            "scalar-field"
        ]);

        json!({
            "$schema": "https://json-schema.org/draft/2020-12/schema",
            "title": "Ezu Style Spec",
            "type": "object",
            "required": ["name", "nodes", "output"],
            "properties": {
                "name": { "type": "string" },
                "version": { "type": "string" },
                "tile-size": { "type": "integer", "minimum": 1 },
                "pad": { "type": "integer", "minimum": 0 },
                "attribution": {
                    "type": "string",
                    "description": "Attribution for the style itself (HTML allowed). Merged with per-source and upstream attributions."
                },
                "params": {
                    "type": "object",
                    "additionalProperties": {
                        "type": "object",
                        "required": ["type", "default"],
                        "properties": {
                            "type": { "enum": ["color", "number", "bool"] },
                            "default": {},
                            "min": { "type": "number" },
                            "max": { "type": "number" },
                            "description": { "type": "string" }
                        }
                    }
                },
                "functions": {
                    "type": "object",
                    "description": "User-defined functions: reusable node subgraphs called via `op: func`.",
                    "additionalProperties": {
                        "type": "object",
                        "required": ["output", "output-kind", "nodes"],
                        "properties": {
                            "description": { "type": "string" },
                            "inputs": {
                                "type": "object",
                                "additionalProperties": {
                                    "type": "object",
                                    "required": ["kind"],
                                    "properties": {
                                        "kind": { "enum": func_kinds.clone() },
                                        "default": {},
                                        "description": { "type": "string" }
                                    }
                                }
                            },
                            "output": {
                                "type": "string",
                                "description": "Body node (with or without `@`) the call produces."
                            },
                            "output-kind": { "enum": func_kinds },
                            "nodes": { "$ref": "#/properties/nodes" }
                        }
                    }
                },
                "sources": {
                    "type": "object",
                    "additionalProperties": {
                        "oneOf": [
                            {
                                "type": "object",
                                "required": ["type", "src"],
                                "properties": {
                                    "type": { "enum": ["brush", "image"] },
                                    "src": { "type": "string" },
                                    "attribution": { "type": "string" }
                                }
                            },
                            {
                                "type": "object",
                                "required": ["type", "url"],
                                "properties": {
                                    "type": { "enum": ["mvt", "pmtiles"] },
                                    "url": { "type": "string" },
                                    "attribution": { "type": "string", "description": "Explicit attribution; inherits upstream TileJSON / PMTiles metadata when absent." }
                                }
                            },
                            {
                                "type": "object",
                                "required": ["type", "url", "encoding"],
                                "properties": {
                                    "type": { "const": "dem" },
                                    "url": { "type": "string", "description": "XYZ template or TileJSON URL." },
                                    "encoding": { "enum": ["terrarium", "mapbox-rgb"] },
                                    "tile-size": { "type": "integer", "minimum": 1 },
                                    "max-zoom": { "type": "integer", "minimum": 0 },
                                    "neighbor-fetch": { "type": "boolean" },
                                    "elevation-offset": { "type": "number" },
                                    "on-missing": { "enum": ["empty", "upsample", "error"], "default": "empty", "description": "404 within zoom range: zero elevation, upsample a parent, or fail the tile." },
                                    "attribution": { "type": "string" }
                                }
                            },
                            {
                                "type": "object",
                                "required": ["type", "url"],
                                "properties": {
                                    "type": { "const": "raster" },
                                    "url": { "type": "string", "description": "XYZ template, TileJSON URL, or PMTiles archive (`.pmtiles`). PNG/WebP/JPEG tiles." },
                                    "max-zoom": { "type": "integer", "minimum": 0 },
                                    "neighbor-fetch": { "type": "boolean" },
                                    "on-missing": { "enum": ["empty", "upsample", "error"], "default": "empty", "description": "404 within zoom range: transparent pixels, upsample a parent, or fail the tile." },
                                    "attribution": { "type": "string" }
                                }
                            }
                        ]
                    }
                },
                "nodes": {
                    "type": "object",
                    "additionalProperties": { "oneOf": variants }
                },
                "output": {
                    "type": "string",
                    "description": "Node id of the final raster (with or without `@`)."
                }
            }
        })
    }
}

/// Pre-built JSON Schema fragments commonly reused by `NodeFactory::schema`
/// implementations.
pub mod schema_frag {
    use serde_json::{json, Value};

    /// A reference to another node, written `@id`.
    pub fn node_ref() -> Value {
        json!({
            "type": "string",
            "pattern": "^@?[A-Za-z_][A-Za-z0-9_-]*$",
            "description": "Reference to another node (`@name`)."
        })
    }

    /// A reference to a registered asset (brush / image / etc.).
    pub fn asset_ref() -> Value {
        json!({
            "type": "string",
            "description": "Asset reference (`@name`) or literal path."
        })
    }

    /// `#rrggbb` or `#rrggbbaa` color literal. Also allows `$param`
    /// and `@node` (scalar port).
    pub fn color() -> Value {
        json!({
            "type": "string",
            "pattern": "^(#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?|[$@][A-Za-z_][A-Za-z0-9_-]*)$",
            "description": "sRGB hex color, `$param` reference, or `@node` scalar port."
        })
    }

    /// Number in `[0, 1]` — commonly opacity / fraction parameters.
    pub fn unit_number() -> Value {
        in_number(json!({ "type": "number", "minimum": 0.0, "maximum": 1.0 }))
    }

    /// Non-negative number in pixels.
    pub fn px_number() -> Value {
        in_number(json!({ "type": "number", "minimum": 0.0 }))
    }

    /// Unconstrained number field.
    pub fn number() -> Value {
        in_number(json!({ "type": "number" }))
    }

    /// Wrap a numeric schema so the field also accepts `$param` /
    /// `@node` reference strings (an [`In<f64>`](crate::input::In)
    /// field).
    pub fn in_number(literal: Value) -> Value {
        json!({
            "oneOf": [
                literal,
                {
                    "type": "string",
                    "pattern": "^[$@][A-Za-z_][A-Za-z0-9_-]*$",
                    "description": "`$param` reference or `@node` scalar port."
                }
            ]
        })
    }
}

/// Helper for factory authors: extract a `@node-ref` from a string field.
///
/// Returns the bare node id (no `@`). Errors if the field is missing,
/// not a string, or not a node reference.
pub fn take_input_ref(
    fields: &serde_json::Map<String, serde_json::Value>,
    name: &str,
) -> Result<String, FactoryError> {
    let v = fields
        .get(name)
        .ok_or_else(|| FactoryError::MissingField(name.to_string()))?;
    let s = v.as_str().ok_or_else(|| FactoryError::BadField {
        field: name.to_string(),
        msg: "expected string node reference".into(),
    })?;
    match spec::FieldRef::classify(s) {
        spec::FieldRef::Node(id) => Ok(id.to_string()),
        _ => Err(FactoryError::BadField {
            field: name.to_string(),
            msg: format!("expected `@node-ref`, got `{s}`"),
        }),
    }
}

/// Like [`take_input_ref`] but returns `None` if the field is absent
/// or JSON `null`. Use for optional input ports.
pub fn take_optional_input_ref(
    fields: &serde_json::Map<String, serde_json::Value>,
    name: &str,
) -> Result<Option<String>, FactoryError> {
    match fields.get(name) {
        None => Ok(None),
        Some(v) if v.is_null() => Ok(None),
        Some(_) => Ok(Some(take_input_ref(fields, name)?)),
    }
}