Skip to main content

egui_pop_viewport/graph/yaml/
mod.rs

1//! A reference [`GraphModel`] kept in a YAML file, for applications that
2//! have no graph model of their own (the `graph-yaml` feature).
3//!
4//! [`YamlGraph`] reads a graph file and is the model the editor draws;
5//! [`YamlGraph::apply`] is its one mutation point: each [`Edit`] the
6//! editor hands back (or a `graph.*` step lets through) changes the
7//! file's text where the edit lands, and nothing else. What the editor
8//! did not touch is written back as it was read: the order of keys,
9//! comments, blank lines, quoting, and keys egui-pop does not know.
10//!
11//! ```yaml
12//! $extensions:
13//!   org.egui-pop.graph: {version: 1}
14//! groups:
15//!   detail: Detail
16//! kinds:
17//!   load:
18//!     title: Load
19//!     outputs: {image: image}
20//!   blur:
21//!     title: Blur
22//!     inputs: {image: image}
23//!     outputs: {image: image}
24//!     params:
25//!       radius: {label: Radius, value: 2, min: 0, max: 20, step: 0.1, unit: px}
26//! nodes:
27//!   - id: load
28//!     kind: load
29//!     pos: [0, 0]
30//!   # Softens the source.
31//!   - id: blur
32//!     kind: blur
33//!     pos: [240, 0]
34//!     group: detail
35//!     params:
36//!       radius: 3.5
37//! edges:
38//!   - load.image -> blur.image
39//! ```
40//!
41//! The format is described in `docs/node-graph.md` ("A graph file").
42
43mod entries;
44mod text;
45
46use std::collections::HashSet;
47use std::fmt;
48
49use serde_json::Value as Json;
50
51use super::{Edge, Edit, GraphModel, Group, Kind, Node, Param, Port, PortRef, PortType};
52use entries::{
53    At, EdgeEntry, EdgeItem, Entries, Field, KindEntry, NodeEntry, ParamEntry, PortEntry, RawFile,
54};
55use text::{
56    Entry, Splices, Text, comment_start, edge_inline, item_keys, items_block, node_lines, num,
57    param_inline, pos, replace_value, sections, seq_items, string, sub_keys,
58};
59
60/// The key of the root `$extensions` that stamps a graph file with the
61/// version of its format: `org.egui-pop.graph: {version: 1}`, as token
62/// files carry `org.egui-pop.format`.
63pub const FORMAT_EXTENSION: &str = "org.egui-pop.graph";
64
65/// The version of the graph format this egui-pop writes. A file
66/// without a stamp is read as this version.
67pub const FORMAT_VERSION: u64 = 1;
68
69/// A new graph's text.
70const EMPTY: &str = "$extensions:\n  org.egui-pop.graph: {version: 1}\nnodes: []\nedges: []\n";
71
72/// Why a graph file cannot be read: what is wrong, and where when that
73/// is known (a line and a column, from 1).
74#[derive(Clone, Debug, PartialEq, Eq)]
75pub struct YamlGraphError {
76    pub line: Option<u64>,
77    pub column: Option<u64>,
78    pub message: String,
79}
80
81impl YamlGraphError {
82    fn at(at: At, message: String) -> YamlGraphError {
83        let at = at.known();
84        YamlGraphError {
85            line: at.map(|a| a.line),
86            column: at.map(|a| a.column),
87            message,
88        }
89    }
90}
91
92impl fmt::Display for YamlGraphError {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        match (self.line, self.column) {
95            (Some(l), Some(c)) => write!(f, "line {l}, column {c}: {}", self.message),
96            (Some(l), None) => write!(f, "line {l}: {}", self.message),
97            _ => f.write_str(&self.message),
98        }
99    }
100}
101
102impl std::error::Error for YamlGraphError {}
103
104/// The graph as the editor reads it.
105#[derive(Clone, Debug, Default, PartialEq)]
106struct Built {
107    nodes: Vec<Node>,
108    edges: Vec<Edge>,
109    params: Vec<(String, Vec<Param>)>,
110    groups: Vec<Group>,
111    kinds: Vec<Kind>,
112}
113
114/// A graph kept in a YAML file: the editor's model, changed by
115/// [`apply`](YamlGraph::apply), written back by [`text`](YamlGraph::text).
116///
117/// ```
118/// use egui_pop_viewport::graph::yaml::YamlGraph;
119/// use egui_pop_viewport::graph::{Edit, GraphModel, Moved};
120///
121/// let src = "nodes:\n  - id: a # the first\n    pos: [0, 0]\n";
122/// let mut graph = YamlGraph::parse(src).unwrap();
123/// assert_eq!(graph.text(), src);
124/// graph.apply(&Edit::Move {
125///     moves: vec![Moved { node: "a".into(), from: [0.0, 0.0], to: [40.0, 10.0] }],
126/// });
127/// assert_eq!(graph.text(), "nodes:\n  - id: a # the first\n    pos: [40, 10]\n");
128/// assert_eq!(graph.nodes()[0].pos, [40.0, 10.0]);
129/// ```
130#[derive(Clone, Debug)]
131pub struct YamlGraph {
132    text: String,
133    entries: Entries,
134    built: Built,
135    version: u64,
136    warnings: Vec<String>,
137}
138
139impl Default for YamlGraph {
140    fn default() -> Self {
141        YamlGraph::empty()
142    }
143}
144
145impl YamlGraph {
146    /// A graph without nodes, its file stamped with [`FORMAT_VERSION`].
147    pub fn empty() -> YamlGraph {
148        YamlGraph::parse(EMPTY).expect("the empty graph reads")
149    }
150
151    /// Reads a graph file. Its text is kept as it is: [`text`](Self::text)
152    /// gives it back byte for byte until an edit.
153    pub fn parse(text: &str) -> Result<YamlGraph, YamlGraphError> {
154        let t = Text::new(text);
155        let secs = sections(&t).map_err(|i| YamlGraphError {
156            line: Some(i as u64 + 1),
157            column: Some(1),
158            message: "the top level must be a block mapping, one `key:` per line".into(),
159        })?;
160        let raw: RawFile = if secs.is_empty() {
161            RawFile::default()
162        } else {
163            serde_saphyr::from_str(text).map_err(|e| {
164                let at = e.location().filter(|l| l.line() > 0);
165                YamlGraphError {
166                    line: at.map(|l| l.line()),
167                    column: at.map(|l| l.column()),
168                    message: e.without_snippet().to_string(),
169                }
170            })?
171        };
172        let entries = Entries::from(raw);
173        let version = version(entries.extensions.as_ref())?;
174        let built = build(&entries)?;
175        let mut warnings = Vec::new();
176        if version > FORMAT_VERSION {
177            warnings.push(format!(
178                "the file is stamped with graph format {version}, newer than {FORMAT_VERSION}: \
179                 it is read as {FORMAT_VERSION}, keys not known are kept as they are"
180            ));
181        }
182        Ok(YamlGraph {
183            text: text.to_string(),
184            entries,
185            built,
186            version,
187            warnings,
188        })
189    }
190
191    /// The file's text: as read, with the edits applied since.
192    pub fn text(&self) -> &str {
193        &self.text
194    }
195
196    /// The format version the file is stamped with ([`FORMAT_VERSION`]
197    /// without a stamp).
198    pub fn version(&self) -> u64 {
199        self.version
200    }
201
202    /// What reading the file noticed without failing (a stamp newer than
203    /// this egui-pop knows).
204    pub fn warnings(&self) -> &[String] {
205        &self.warnings
206    }
207
208    /// A parameter's value.
209    pub fn param(&self, node: &str, param: &str) -> Option<f64> {
210        self.built
211            .params
212            .iter()
213            .find(|(n, _)| n == node)?
214            .1
215            .iter()
216            .find(|p| p.id == param)
217            .map(|p| p.value)
218    }
219
220    /// Applies an edit: the one place the graph changes. Returns whether
221    /// it did (an edit naming a node, port or parameter the file does
222    /// not have, or a kind it does not declare, changes nothing).
223    ///
224    /// The text changes only where the edit lands: a moved node's `pos`,
225    /// a parameter's value, the items of the nodes and wires deleted, new
226    /// items after the last of their list. A part that is not in block
227    /// style (a flow mapping or sequence) is written again whole, in
228    /// block style, when an edit reaches into it; comments inside it are
229    /// lost.
230    ///
231    /// Each edit is one gesture (a drag's `Move` comes at its end; a
232    /// slider's frames come with `done: false`): an application that
233    /// keeps an undo history records [`text`](Self::text) before an edit
234    /// and reads it back to undo.
235    pub fn apply(&mut self, edit: &Edit) -> bool {
236        let Some(after) = self.changed(edit) else {
237            return false;
238        };
239        if after == self.entries {
240            return false;
241        }
242        let Ok(expected) = build(&after) else {
243            return false;
244        };
245        let doc = {
246            let t = Text::new(&self.text);
247            let candidates: [&dyn Fn() -> Option<String>; 2] =
248                [&|| self.splice(&t, edit, &after), &|| rewrite(&t, &after)];
249            // Read back: the text must give the graph the edit makes.
250            candidates.into_iter().find_map(|candidate| {
251                YamlGraph::parse(&candidate()?)
252                    .ok()
253                    .filter(|doc| doc.built == expected)
254            })
255        };
256        match doc {
257            Some(doc) => {
258                *self = doc;
259                true
260            }
261            None => false,
262        }
263    }
264
265    /// The entries once the edit is made; `None` when it names what is
266    /// not there.
267    fn changed(&self, edit: &Edit) -> Option<Entries> {
268        let mut e = self.entries.clone();
269        match edit {
270            Edit::Move { moves } => {
271                for m in moves {
272                    let n = e.nodes.iter_mut().find(|n| n.id() == m.node)?;
273                    if n.field("pos") != Some(&Field::Pos(m.to)) {
274                        n.set("pos", Field::Pos(m.to));
275                    }
276                }
277            }
278            Edit::Param {
279                node, param, to, ..
280            } => {
281                self.param(node, param)?;
282                let n = e.nodes.iter_mut().find(|n| n.id() == node)?;
283                let mut params = match n.field("params") {
284                    Some(Field::Params(p)) => p.clone(),
285                    _ => Vec::new(),
286                };
287                match params.iter_mut().find(|(id, _)| id == param) {
288                    Some((_, ParamEntry::Value(v))) => *v = *to,
289                    Some((_, ParamEntry::Full(f))) => set_json(f, "value", Json::from(*to)),
290                    None => params.push((param.clone(), ParamEntry::Value(*to))),
291                }
292                n.set("params", Field::Params(params));
293            }
294            Edit::Delete { .. } | Edit::Disconnect { .. } | Edit::Connect { .. } => {
295                e.nodes.retain(|n| !drops_node(edit, n.id()));
296                e.edges.retain(|x| !drops_edge(edit, &x.entry));
297                if let Edit::Connect { from, to, .. } = edit {
298                    e.edges.push(EdgeItem {
299                        entry: EdgeEntry::Text(edge_text(&Edge::new(from.clone(), to.clone()))),
300                        at: At::default(),
301                    });
302                }
303            }
304            Edit::Add { nodes } => {
305                for new in nodes {
306                    if !e.kinds.iter().any(|(k, _)| *k == new.kind) {
307                        continue;
308                    }
309                    let id = (1..)
310                        .map(|k| format!("{}-{k}", new.kind))
311                        .find(|id| !e.nodes.iter().any(|n| n.id() == id))
312                        .unwrap_or_default();
313                    let mut fields = vec![
314                        ("id".to_string(), Field::Id(id)),
315                        ("kind".to_string(), Field::Kind(new.kind.clone())),
316                        ("pos".to_string(), Field::Pos(new.at)),
317                    ];
318                    let source = new
319                        .copy_of
320                        .as_ref()
321                        .and_then(|c| e.nodes.iter().find(|n| n.id() == c));
322                    if let Some(source) = source {
323                        for key in ["group", "params"] {
324                            if let Some(f) = source.field(key) {
325                                fields.push((key.to_string(), f.clone()));
326                            }
327                        }
328                    }
329                    e.nodes.push(NodeEntry {
330                        at: At::default(),
331                        fields,
332                    });
333                }
334            }
335        }
336        Some(e)
337    }
338
339    /// The text with the edit spliced in where it lands; `None` when the
340    /// lines it reaches are not in block style.
341    fn splice(&self, t: &Text<'_>, edit: &Edit, after: &Entries) -> Option<String> {
342        let secs = sections(t).ok()?;
343        let items = |key: &str, count: usize| -> Option<Vec<Entry>> {
344            let v = seq_items(t, secs.iter().find(|s| s.key == key)?)?;
345            (v.len() == count).then_some(v)
346        };
347        let nodes = &self.entries.nodes;
348        let index = |id: &str| nodes.iter().position(|n| n.id() == id);
349        let mut s = Splices::default();
350        match edit {
351            Edit::Move { moves } => {
352                let items = items("nodes", nodes.len())?;
353                for m in moves {
354                    let i = index(&m.node)?;
355                    splice_pos(t, &mut s, &items[i], &after.nodes[i], m.to)?;
356                }
357            }
358            Edit::Param {
359                node, param, to, ..
360            } => {
361                let items = items("nodes", nodes.len())?;
362                let i = index(node)?;
363                splice_param(t, &mut s, &items[i], &after.nodes[i], param, *to)?;
364            }
365            Edit::Delete { .. } | Edit::Disconnect { .. } | Edit::Connect { .. } => {
366                let gone: Vec<usize> = (0..nodes.len())
367                    .filter(|&i| drops_node(edit, nodes[i].id()))
368                    .collect();
369                if !gone.is_empty() {
370                    let items = items("nodes", nodes.len())?;
371                    for i in gone {
372                        s.lines(t, items[i].lead, items[i].end, "");
373                    }
374                }
375                let edges = &self.entries.edges;
376                let gone: Vec<usize> = (0..edges.len())
377                    .filter(|&i| drops_edge(edit, &edges[i].entry))
378                    .collect();
379                if !gone.is_empty() {
380                    let items = items("edges", edges.len())?;
381                    for i in gone {
382                        s.lines(t, items[i].lead, items[i].end, "");
383                    }
384                }
385                if let Edit::Connect { .. } = edit {
386                    let new = vec![edge_inline(&after.edges.last()?.entry)];
387                    append(t, &mut s, &secs, "edges", edges.len(), &[new])?;
388                }
389            }
390            Edit::Add { .. } => {
391                let new: Vec<Vec<String>> =
392                    after.nodes[nodes.len()..].iter().map(node_lines).collect();
393                append(t, &mut s, &secs, "nodes", nodes.len(), &new)?;
394            }
395        }
396        Some(s.apply(t.src))
397    }
398}
399
400impl GraphModel for YamlGraph {
401    fn nodes(&self) -> Vec<Node> {
402        self.built.nodes.clone()
403    }
404
405    fn edges(&self) -> Vec<Edge> {
406        self.built.edges.clone()
407    }
408
409    fn groups(&self) -> Vec<Group> {
410        self.built.groups.clone()
411    }
412
413    fn params(&self, node: &str) -> Vec<Param> {
414        self.built
415            .params
416            .iter()
417            .find(|(n, _)| n == node)
418            .map(|(_, p)| p.clone())
419            .unwrap_or_default()
420    }
421
422    fn kinds(&self) -> Vec<Kind> {
423        self.built.kinds.clone()
424    }
425}
426
427/// Whether the edit removes this node.
428fn drops_node(edit: &Edit, id: &str) -> bool {
429    matches!(edit, Edit::Delete { nodes, .. } if nodes.iter().any(|n| n == id))
430}
431
432/// Whether the edit removes this wire (a deleted node takes its wires).
433fn drops_edge(edit: &Edit, e: &EdgeEntry) -> bool {
434    let Some(ed) = edge_of(e) else {
435        return false;
436    };
437    match edit {
438        Edit::Delete { nodes, edges } => edges.contains(&ed) || nodes.iter().any(|n| ed.touches(n)),
439        Edit::Disconnect { edges } => edges.contains(&ed),
440        Edit::Connect { replaces, .. } => replaces.contains(&ed),
441        _ => false,
442    }
443}
444
445/// The node's item with its `pos` set.
446fn splice_pos(
447    t: &Text<'_>,
448    s: &mut Splices,
449    item: &Entry,
450    after: &NodeEntry,
451    to: [f32; 2],
452) -> Option<()> {
453    let Some(keys) = item_keys(t, item) else {
454        rewrite_item(t, s, item, after);
455        return Some(());
456    };
457    match keys.iter().find(|k| k.key == "pos") {
458        Some(k)
459            if k.entry.end == k.entry.start + 1
460                && !t.inline_value(k.entry.start, k.col)?.is_empty() =>
461        {
462            let line = replace_value(t.content(k.entry.start), k.col, &pos(to))?;
463            s.line(t, k.entry.start, line);
464        }
465        Some(k) => {
466            let head = &t.content(k.entry.start)[..k.col];
467            s.lines(
468                t,
469                k.entry.start,
470                k.entry.end,
471                &format!("{head}pos: {}\n", pos(to)),
472            );
473        }
474        None => {
475            let pad = " ".repeat(keys.first()?.col);
476            s.insert(t, item.end, &format!("{pad}pos: {}\n", pos(to)));
477        }
478    }
479    Some(())
480}
481
482/// The node's item with a parameter's value set.
483fn splice_param(
484    t: &Text<'_>,
485    s: &mut Splices,
486    item: &Entry,
487    after: &NodeEntry,
488    param: &str,
489    to: f64,
490) -> Option<()> {
491    let entry = match after.field("params") {
492        Some(Field::Params(ps)) => ps.iter().find(|(id, _)| id == param)?.1.clone(),
493        _ => return None,
494    };
495    let Some(keys) = item_keys(t, item) else {
496        rewrite_item(t, s, item, after);
497        return Some(());
498    };
499    let Some(pk) = keys.iter().find(|k| k.key == "params") else {
500        let col = keys.first()?.col;
501        s.insert(
502            t,
503            item.end,
504            &format!(
505                "{}params:\n{}{}: {}\n",
506                " ".repeat(col),
507                " ".repeat(col + 2),
508                string(param),
509                param_inline(&entry)
510            ),
511        );
512        return Some(());
513    };
514    let Some((col, subs)) = sub_keys(t, pk) else {
515        rewrite_item(t, s, item, after);
516        return Some(());
517    };
518    match subs.iter().find(|k| k.key == param) {
519        None => {
520            let pad = " ".repeat(col.unwrap_or(pk.col + 2));
521            s.insert(
522                t,
523                pk.entry.end,
524                &format!("{pad}{}: {}\n", string(param), param_inline(&entry)),
525            );
526        }
527        Some(k) if k.entry.end == k.entry.start + 1 => {
528            let line = replace_value(t.content(k.entry.start), k.col, &param_inline(&entry))?;
529            s.line(t, k.entry.start, line);
530        }
531        Some(k) => match sub_keys(t, k) {
532            Some((vcol, vkeys)) => match vkeys.iter().find(|v| v.key == "value") {
533                Some(v) if v.entry.end == v.entry.start + 1 => {
534                    let line = replace_value(t.content(v.entry.start), v.col, &num(to))?;
535                    s.line(t, v.entry.start, line);
536                }
537                Some(_) => rewrite_item(t, s, item, after),
538                None => {
539                    let pad = " ".repeat(vcol.unwrap_or(k.col + 2));
540                    s.insert(t, k.entry.end, &format!("{pad}value: {}\n", num(to)));
541                }
542            },
543            None => rewrite_item(t, s, item, after),
544        },
545    }
546    Some(())
547}
548
549/// A node's item written again whole, in block style.
550fn rewrite_item(t: &Text<'_>, s: &mut Splices, item: &Entry, node: &NodeEntry) {
551    let block = items_block(t.indent(item.start), &[node_lines(node)]);
552    s.lines(t, item.start, item.end, &block);
553}
554
555/// New items after the last of a section's list (`count` items there
556/// now), the section written when the list is empty or missing.
557fn append(
558    t: &Text<'_>,
559    s: &mut Splices,
560    secs: &[text::Section],
561    key: &str,
562    count: usize,
563    new: &[Vec<String>],
564) -> Option<()> {
565    if new.is_empty() {
566        return Some(());
567    }
568    let Some(sec) = secs.iter().find(|x| x.key == key) else {
569        s.insert(
570            t,
571            t.lines.len(),
572            &format!("{key}:\n{}", items_block(2, new)),
573        );
574        return Some(());
575    };
576    let items = seq_items(t, sec)?;
577    if items.len() != count {
578        return None;
579    }
580    match items.last() {
581        Some(last) => s.insert(t, last.end, &items_block(t.indent(last.start), new)),
582        None => {
583            let c = t.content(sec.header);
584            let comment = comment_start(c)
585                .map(|i| format!(" {}", &c[i..]))
586                .unwrap_or_default();
587            s.lines(
588                t,
589                sec.header,
590                sec.header + 1,
591                &format!("{key}:{comment}\n{}", items_block(2, new)),
592            );
593        }
594    }
595    Some(())
596}
597
598/// The text with its `nodes` and `edges` written again whole, in block
599/// style: what an edit falls back to when its splice does not read back
600/// as it should. Comments inside these two lists are lost; the rest of
601/// the file is kept.
602fn rewrite(t: &Text<'_>, after: &Entries) -> Option<String> {
603    let secs = sections(t).ok()?;
604    let nodes: Vec<Vec<String>> = after.nodes.iter().map(node_lines).collect();
605    let edges: Vec<Vec<String>> = after
606        .edges
607        .iter()
608        .map(|e| vec![edge_inline(&e.entry)])
609        .collect();
610    let mut s = Splices::default();
611    for (key, items) in [("nodes", nodes), ("edges", edges)] {
612        let block = if items.is_empty() {
613            format!("{key}: []\n")
614        } else {
615            format!("{key}:\n{}", items_block(2, &items))
616        };
617        match secs.iter().find(|x| x.key == key) {
618            Some(sec) => {
619                let end = t
620                    .content_end(sec.header + 1, sec.end)
621                    .unwrap_or(sec.header + 1);
622                s.lines(t, sec.header, end, &block);
623            }
624            None => s.insert(t, t.lines.len(), &block),
625        }
626    }
627    Some(s.apply(t.src))
628}
629
630fn set_json(fields: &mut Vec<(String, Json)>, key: &str, value: Json) {
631    match fields.iter_mut().find(|(k, _)| k == key) {
632        Some((_, v)) => *v = value,
633        None => fields.push((key.to_string(), value)),
634    }
635}
636
637fn get<'a>(fields: &'a [(String, Json)], key: &str) -> Option<&'a Json> {
638    fields.iter().find(|(k, _)| k == key).map(|(_, v)| v)
639}
640
641/// `node.port`: the port's id after the last dot.
642fn port_ref(s: &str) -> Option<PortRef> {
643    let (node, port) = s.trim().rsplit_once('.')?;
644    let (node, port) = (node.trim(), port.trim());
645    (!node.is_empty() && !port.is_empty()).then(|| PortRef::new(node, port))
646}
647
648/// The wire an entry names, when it is written as one.
649fn edge_of(e: &EdgeEntry) -> Option<Edge> {
650    match e {
651        EdgeEntry::Text(s) => {
652            let (from, to) = s.split_once("->")?;
653            Some(Edge::new(port_ref(from)?, port_ref(to)?))
654        }
655        EdgeEntry::Map(f) => Some(Edge::new(
656            port_ref(get(f, "from")?.as_str()?)?,
657            port_ref(get(f, "to")?.as_str()?)?,
658        )),
659    }
660}
661
662fn edge_text(e: &Edge) -> String {
663    format!(
664        "{}.{} -> {}.{}",
665        e.from.node, e.from.port, e.to.node, e.to.port
666    )
667}
668
669/// A port's or a parameter's label when the file gives none: its id,
670/// capitalised.
671fn label_of(id: &str) -> String {
672    let mut c = id.chars();
673    c.next()
674        .map(|f| f.to_uppercase().chain(c).collect())
675        .unwrap_or_default()
676}
677
678/// The stamp's version.
679fn version(extensions: Option<&Json>) -> Result<u64, YamlGraphError> {
680    let Some(stamp) = extensions.and_then(|x| x.get(FORMAT_EXTENSION)) else {
681        return Ok(FORMAT_VERSION);
682    };
683    stamp
684        .get("version")
685        .and_then(Json::as_u64)
686        .filter(|v| *v > 0)
687        .ok_or_else(|| YamlGraphError {
688            line: None,
689            column: None,
690            message: format!(
691                "`$extensions: {FORMAT_EXTENSION}` needs a `version`, a whole number from 1"
692            ),
693        })
694}
695
696fn port(node: &str, id: &str, p: &PortEntry) -> Result<Port, String> {
697    let f = match p {
698        PortEntry::Type(t) => return Ok(Port::new(id, label_of(id), PortType::new(t.as_str()))),
699        PortEntry::Full(f) => f,
700    };
701    let text = |key: &str| -> Result<Option<&str>, String> {
702        get(f, key)
703            .map(|v| {
704                v.as_str()
705                    .ok_or_else(|| format!("node `{node}`: port `{id}`: `{key}` is not a string"))
706            })
707            .transpose()
708    };
709    let ty = text("type")?.ok_or_else(|| format!("node `{node}`: port `{id}` needs a `type`"))?;
710    let mut ty = PortType::new(ty);
711    if let Some(c) = text("color")? {
712        ty = ty.color(c);
713    }
714    let label = text("label")?.map_or_else(|| label_of(id), str::to_string);
715    let mut port = Port::new(id, label, ty);
716    match get(f, "multiple") {
717        None | Some(Json::Bool(false)) => {}
718        Some(Json::Bool(true)) => port = port.multiple(),
719        Some(_) => {
720            return Err(format!(
721                "node `{node}`: port `{id}`: `multiple` is not true or false"
722            ));
723        }
724    }
725    Ok(port)
726}
727
728/// A kind's ports with a node's own: a node's port of the same id
729/// replaces the kind's, others come after.
730fn ports(
731    node: &str,
732    base: &[(String, PortEntry)],
733    own: Option<&Field>,
734) -> Result<Vec<Port>, String> {
735    let mut all: Vec<(String, PortEntry)> = base.to_vec();
736    if let Some(Field::Inputs(own) | Field::Outputs(own)) = own {
737        for (id, p) in own {
738            match all.iter_mut().find(|(k, _)| k == id) {
739                Some((_, slot)) => *slot = p.clone(),
740                None => all.push((id.clone(), p.clone())),
741            }
742        }
743    }
744    all.iter().map(|(id, p)| port(node, id, p)).collect()
745}
746
747fn param_fields(p: &ParamEntry) -> Vec<(String, Json)> {
748    match p {
749        ParamEntry::Value(v) => vec![("value".to_string(), Json::from(*v))],
750        ParamEntry::Full(f) => f.clone(),
751    }
752}
753
754/// A kind's parameters with a node's: a node's fields over the kind's
755/// (a number alone sets the value), its own parameters after. The
756/// kind's value is the default a double click goes back to.
757fn params(
758    node: &str,
759    base: &[(String, ParamEntry)],
760    own: Option<&Field>,
761) -> Result<Vec<Param>, String> {
762    // Each parameter's fields, and the kind's value.
763    type Merged = (String, Vec<(String, Json)>, Option<f64>);
764    let mut all: Vec<Merged> = base
765        .iter()
766        .map(|(id, p)| {
767            let fields = param_fields(p);
768            let value = get(&fields, "value").and_then(Json::as_f64);
769            (id.clone(), fields, value)
770        })
771        .collect();
772    if let Some(Field::Params(own)) = own {
773        for (id, p) in own {
774            match all.iter_mut().find(|(k, _, _)| k == id) {
775                Some((_, fields, _)) => {
776                    for (k, v) in param_fields(p) {
777                        set_json(fields, &k, v);
778                    }
779                }
780                None => all.push((id.clone(), param_fields(p), None)),
781            }
782        }
783    }
784    all.iter()
785        .map(|(id, f, kind_value)| {
786            let number = |key: &str| -> Result<Option<f64>, String> {
787                get(f, key)
788                    .map(|v| {
789                        v.as_f64().ok_or_else(|| {
790                            format!("node `{node}`: parameter `{id}`: `{key}` is not a number")
791                        })
792                    })
793                    .transpose()
794            };
795            let text = |key: &str| -> Result<Option<&str>, String> {
796                get(f, key)
797                    .map(|v| {
798                        v.as_str().ok_or_else(|| {
799                            format!("node `{node}`: parameter `{id}`: `{key}` is not a string")
800                        })
801                    })
802                    .transpose()
803            };
804            let (Some(min), Some(max)) = (number("min")?, number("max")?) else {
805                return Err(format!(
806                    "node `{node}`: parameter `{id}` needs a `min` and a `max`"
807                ));
808            };
809            if min > max {
810                return Err(format!(
811                    "node `{node}`: parameter `{id}`: `min` is above `max`"
812                ));
813            }
814            let default = number("default")?.or(*kind_value);
815            let value = number("value")?.or(default).unwrap_or(min);
816            let label = text("label")?.map_or_else(|| label_of(id), str::to_string);
817            let mut p = Param::new(id.as_str(), label, value, min..=max);
818            if let Some(step) = number("step")? {
819                p = p.step(step);
820            }
821            if let Some(unit) = text("unit")? {
822                p = p.unit(unit);
823            }
824            if let Some(d) = default {
825                p = p.default(d);
826            }
827            Ok(p)
828        })
829        .collect()
830}
831
832/// The graph the entries describe, or the first thing wrong in them,
833/// with where it was written.
834fn build(e: &Entries) -> Result<Built, YamlGraphError> {
835    let groups: Vec<Group> = e
836        .groups
837        .iter()
838        .map(|(id, g)| Group::new(id.as_str(), g.0.clone().unwrap_or_else(|| id.clone())))
839        .collect();
840    let kinds: Vec<Kind> = e
841        .kinds
842        .iter()
843        .map(|(id, k)| Kind::new(id.as_str(), k.title.clone().unwrap_or_else(|| id.clone())))
844        .collect();
845    let mut seen = HashSet::new();
846    let mut nodes = Vec::with_capacity(e.nodes.len());
847    let mut all_params = Vec::with_capacity(e.nodes.len());
848    let empty = KindEntry::default();
849    for n in &e.nodes {
850        let id = n.id();
851        let err = |message: String| YamlGraphError::at(n.at, message);
852        if id.is_empty() {
853            return Err(err("a node's `id` is empty".into()));
854        }
855        if !seen.insert(id) {
856            return Err(err(format!("a second node `{id}`")));
857        }
858        let (kind_id, kind) = match n.field("kind") {
859            Some(Field::Kind(k)) => {
860                let kind = e
861                    .kinds
862                    .iter()
863                    .find(|(id, _)| id == k)
864                    .map(|(_, d)| d)
865                    .ok_or_else(|| err(format!("node `{id}`: no kind `{k}` in `kinds`")))?;
866                (k.as_str(), kind)
867            }
868            _ => ("", &empty),
869        };
870        let title = match n.field("title") {
871            Some(Field::Title(t)) => t.clone(),
872            _ => kind.title.clone().unwrap_or_else(|| id.to_string()),
873        };
874        let at = match n.field("pos") {
875            Some(Field::Pos(p)) => *p,
876            _ => [0.0, 0.0],
877        };
878        let mut node = Node::new(id, kind_id, title, at);
879        if let Some(Field::Group(g)) = n.field("group") {
880            if !e.groups.iter().any(|(id, _)| id == g) {
881                return Err(err(format!("node `{id}`: no group `{g}` in `groups`")));
882            }
883            node = node.group(g.as_str());
884        }
885        node.inputs = ports(id, &kind.inputs.0, n.field("inputs")).map_err(err)?;
886        node.outputs = ports(id, &kind.outputs.0, n.field("outputs")).map_err(err)?;
887        all_params.push((
888            id.to_string(),
889            params(id, &kind.params.0, n.field("params")).map_err(err)?,
890        ));
891        nodes.push(node);
892    }
893    let mut edges = Vec::with_capacity(e.edges.len());
894    for item in &e.edges {
895        let err = |message: String| YamlGraphError::at(item.at, message);
896        let edge = edge_of(&item.entry).ok_or_else(|| {
897            err("a wire is `node.port -> node.port`, or a mapping with `from` and `to`".into())
898        })?;
899        let name = edge_text(&edge);
900        let end = |r: &PortRef, output: bool| -> Result<(), YamlGraphError> {
901            let node = nodes
902                .iter()
903                .find(|n| n.id == r.node)
904                .ok_or_else(|| err(format!("wire `{name}`: no node `{}`", r.node)))?;
905            let ports = if output { &node.outputs } else { &node.inputs };
906            if ports.iter().any(|p| p.id == r.port) {
907                Ok(())
908            } else {
909                let side = if output { "output" } else { "input" };
910                Err(err(format!(
911                    "wire `{name}`: no {side} `{}` on node `{}`",
912                    r.port, r.node
913                )))
914            }
915        };
916        end(&edge.from, true)?;
917        end(&edge.to, false)?;
918        edges.push(edge);
919    }
920    Ok(Built {
921        nodes,
922        edges,
923        params: all_params,
924        groups,
925        kinds,
926    })
927}