Skip to main content

egui_pop_viewport/graph/
model.rs

1//! The graph an application supplies ([`GraphModel`]), and what the
2//! editor hands back: the [`Edit`]s it proposes, the [`Request`]s it
3//! takes from outside and the [`GraphEvent`]s it reports.
4//!
5//! Identifiers are strings the application chooses: a node's `id`, a
6//! port's `id` within its node, a group's `id`, a kind's `id`. They are
7//! what steps, commands and the debug bridge show, so they stay readable.
8
9use std::ops::RangeInclusive;
10
11use serde_json::{Value as Json, json};
12
13/// A port of a node: a node's id and the port's id within it.
14#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
15pub struct PortRef {
16    pub node: String,
17    pub port: String,
18}
19
20impl PortRef {
21    pub fn new(node: impl Into<String>, port: impl Into<String>) -> PortRef {
22        PortRef {
23            node: node.into(),
24            port: port.into(),
25        }
26    }
27
28    /// `{"node": ..., "port": ...}`.
29    pub fn to_json(&self) -> Json {
30        json!({ "node": self.node, "port": self.port })
31    }
32
33    pub fn from_json(v: &Json) -> Option<PortRef> {
34        Some(PortRef::new(
35            v.get("node")?.as_str()?,
36            v.get("port")?.as_str()?,
37        ))
38    }
39}
40
41/// A wire, from an output to an input.
42#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
43pub struct Edge {
44    pub from: PortRef,
45    pub to: PortRef,
46}
47
48impl Edge {
49    pub fn new(from: PortRef, to: PortRef) -> Edge {
50        Edge { from, to }
51    }
52
53    /// `{"from": {node, port}, "to": {node, port}}`.
54    pub fn to_json(&self) -> Json {
55        json!({ "from": self.from.to_json(), "to": self.to.to_json() })
56    }
57
58    pub fn from_json(v: &Json) -> Option<Edge> {
59        Some(Edge::new(
60            PortRef::from_json(v.get("from")?)?,
61            PortRef::from_json(v.get("to")?)?,
62        ))
63    }
64
65    /// Whether the wire touches a node.
66    pub fn touches(&self, node: &str) -> bool {
67        self.from.node == node || self.to.node == node
68    }
69}
70
71/// The colour tokens a port type takes by default, one picked from its
72/// name (`graph.type-1` to `graph.type-6`).
73pub const TYPE_TOKENS: [&str; 6] = [
74    "graph.type-1",
75    "graph.type-2",
76    "graph.type-3",
77    "graph.type-4",
78    "graph.type-5",
79    "graph.type-6",
80];
81
82/// What flows through a port (`image`, `mask`, `number`), and the token
83/// its ports and wires are drawn with.
84#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct PortType {
86    pub name: String,
87    /// A colour token's path (`graph.type-2`, or one of the
88    /// application's own tokens).
89    pub color: String,
90}
91
92impl PortType {
93    /// A type coloured by one of [`TYPE_TOKENS`], the same for the same
94    /// name.
95    pub fn new(name: impl Into<String>) -> PortType {
96        let name = name.into();
97        let h = name
98            .bytes()
99            .fold(0u32, |h, b| h.wrapping_mul(31).wrapping_add(u32::from(b)));
100        let color = TYPE_TOKENS[(h % TYPE_TOKENS.len() as u32) as usize].to_string();
101        PortType { name, color }
102    }
103
104    /// Drawn with this colour token instead.
105    pub fn color(mut self, token: impl Into<String>) -> PortType {
106        self.color = token.into();
107        self
108    }
109}
110
111/// Which side of a node a port is on.
112#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
113pub enum Side {
114    Input,
115    Output,
116}
117
118impl Side {
119    pub fn name(self) -> &'static str {
120        match self {
121            Side::Input => "input",
122            Side::Output => "output",
123        }
124    }
125}
126
127/// A port: where a wire ends (an input) or starts (an output).
128#[derive(Clone, Debug, PartialEq)]
129pub struct Port {
130    pub id: String,
131    pub label: String,
132    pub ty: PortType,
133    /// An input taking several wires. By default an input takes one,
134    /// and a new wire replaces the old one; an output always feeds any
135    /// number.
136    pub multiple: bool,
137}
138
139impl Port {
140    pub fn new(id: impl Into<String>, label: impl Into<String>, ty: PortType) -> Port {
141        Port {
142            id: id.into(),
143            label: label.into(),
144            ty,
145            multiple: false,
146        }
147    }
148
149    /// An input taking several wires.
150    pub fn multiple(mut self) -> Port {
151        self.multiple = true;
152        self
153    }
154}
155
156/// A node as the application describes it.
157#[derive(Clone, Debug, PartialEq)]
158pub struct Node {
159    pub id: String,
160    /// What it is (`blur`, `load`): what a duplicate or an addition
161    /// names.
162    pub kind: String,
163    pub title: String,
164    /// Its top-left corner, in graph units (points at 100 %).
165    pub pos: [f32; 2],
166    pub inputs: Vec<Port>,
167    pub outputs: Vec<Port>,
168    /// The group it belongs to.
169    pub group: Option<String>,
170}
171
172impl Node {
173    pub fn new(
174        id: impl Into<String>,
175        kind: impl Into<String>,
176        title: impl Into<String>,
177        pos: [f32; 2],
178    ) -> Node {
179        Node {
180            id: id.into(),
181            kind: kind.into(),
182            title: title.into(),
183            pos,
184            inputs: Vec::new(),
185            outputs: Vec::new(),
186            group: None,
187        }
188    }
189
190    pub fn input(mut self, port: Port) -> Node {
191        self.inputs.push(port);
192        self
193    }
194
195    pub fn output(mut self, port: Port) -> Node {
196        self.outputs.push(port);
197        self
198    }
199
200    pub fn group(mut self, group: impl Into<String>) -> Node {
201        self.group = Some(group.into());
202        self
203    }
204
205    /// A port by side and id.
206    pub fn port(&self, side: Side, id: &str) -> Option<&Port> {
207        match side {
208            Side::Input => &self.inputs,
209            Side::Output => &self.outputs,
210        }
211        .iter()
212        .find(|p| p.id == id)
213    }
214}
215
216/// A group of nodes: drawn as a frame around them, or folded into a
217/// stack.
218#[derive(Clone, Debug, PartialEq)]
219pub struct Group {
220    pub id: String,
221    pub label: String,
222}
223
224impl Group {
225    pub fn new(id: impl Into<String>, label: impl Into<String>) -> Group {
226        Group {
227            id: id.into(),
228            label: label.into(),
229        }
230    }
231}
232
233/// A node's parameter, edited inline with a slider in the detail view.
234#[derive(Clone, Debug, PartialEq)]
235pub struct Param {
236    pub id: String,
237    pub label: String,
238    pub value: f64,
239    /// What the bar spans.
240    pub range: RangeInclusive<f64>,
241    /// The arrows' step (and the precision shown).
242    pub step: Option<f64>,
243    pub unit: Option<String>,
244    /// What a double click goes back to.
245    pub default: Option<f64>,
246}
247
248impl Param {
249    pub fn new(
250        id: impl Into<String>,
251        label: impl Into<String>,
252        value: f64,
253        range: RangeInclusive<f64>,
254    ) -> Param {
255        Param {
256            id: id.into(),
257            label: label.into(),
258            value,
259            range,
260            step: None,
261            unit: None,
262            default: None,
263        }
264    }
265
266    pub fn step(mut self, step: f64) -> Param {
267        self.step = Some(step);
268        self
269    }
270
271    pub fn unit(mut self, unit: impl Into<String>) -> Param {
272        self.unit = Some(unit.into());
273        self
274    }
275
276    pub fn default(mut self, default: f64) -> Param {
277        self.default = Some(default);
278        self
279    }
280}
281
282/// A kind of node the user may add (the canvas's menu).
283#[derive(Clone, Debug, PartialEq)]
284pub struct Kind {
285    pub id: String,
286    pub title: String,
287}
288
289impl Kind {
290    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Kind {
291        Kind {
292            id: id.into(),
293            title: title.into(),
294        }
295    }
296}
297
298/// Why a wire is refused.
299#[derive(Clone, Debug, PartialEq)]
300pub enum Refusal {
301    /// The output's type is not the input's.
302    Types { from: String, to: String },
303    /// A node cannot feed itself.
304    SameNode,
305    /// Two inputs, or two outputs.
306    SameSide,
307    /// The wire is there already (nothing to do; never reported).
308    Exists,
309    /// The application's own reason, shown as is.
310    Other(String),
311}
312
313/// The default type check: an output feeds an input of the same type,
314/// on another node.
315pub fn check(from: (&Node, &Port), to: (&Node, &Port)) -> Result<(), Refusal> {
316    if from.0.id == to.0.id {
317        return Err(Refusal::SameNode);
318    }
319    if from.1.ty.name != to.1.ty.name {
320        return Err(Refusal::Types {
321            from: from.1.ty.name.clone(),
322            to: to.1.ty.name.clone(),
323        });
324    }
325    Ok(())
326}
327
328/// The graph, as the application keeps it. The editor reads it each
329/// frame and never changes it: what the user does comes back as
330/// [`Edit`]s for the application to apply.
331pub trait GraphModel {
332    /// Every node, in drawing order (the last on top).
333    fn nodes(&self) -> Vec<Node>;
334
335    /// Every wire.
336    fn edges(&self) -> Vec<Edge>;
337
338    /// The groups nodes name.
339    fn groups(&self) -> Vec<Group> {
340        Vec::new()
341    }
342
343    /// A node's parameters, shown in the detail view.
344    fn params(&self, _node: &str) -> Vec<Param> {
345        Vec::new()
346    }
347
348    /// The kinds of node the canvas's menu offers to add.
349    fn kinds(&self) -> Vec<Kind> {
350        Vec::new()
351    }
352
353    /// Whether an output may feed an input; by default [`check`] (same
354    /// type, another node).
355    fn can_connect(&self, from: (&Node, &Port), to: (&Node, &Port)) -> Result<(), Refusal> {
356        check(from, to)
357    }
358}
359
360/// A node moved: where it was and where it goes.
361#[derive(Clone, Debug, PartialEq)]
362pub struct Moved {
363    pub node: String,
364    pub from: [f32; 2],
365    pub to: [f32; 2],
366}
367
368/// A node to add: its kind and place, or a copy of another node.
369#[derive(Clone, Debug, PartialEq)]
370pub struct NewNode {
371    pub kind: String,
372    pub at: [f32; 2],
373    /// The node it duplicates (with its parameters), if any.
374    pub copy_of: Option<String>,
375}
376
377/// What the editor asks the application to do to its graph.
378#[non_exhaustive]
379#[derive(Clone, Debug, PartialEq)]
380pub enum Edit {
381    /// A wire from an output to an input; `replaces` are the wires it
382    /// takes the place of (the input's old wire, or the wire whose end
383    /// was moved), to remove first: a reconnection is one edit.
384    Connect {
385        from: PortRef,
386        to: PortRef,
387        replaces: Vec<Edge>,
388    },
389    /// Wires to remove.
390    Disconnect { edges: Vec<Edge> },
391    /// Nodes moved (one gesture).
392    Move { moves: Vec<Moved> },
393    /// Nodes to delete, with the wires touching them.
394    Delete {
395        nodes: Vec<String>,
396        edges: Vec<Edge>,
397    },
398    /// Nodes to add (from the menu, a command, or a duplicate).
399    Add { nodes: Vec<NewNode> },
400    /// A parameter's slider moved: a drag's frames with `done: false`,
401    /// its end once more from the value before it with `done: true`.
402    Param {
403        node: String,
404        param: String,
405        from: f64,
406        to: f64,
407        done: bool,
408    },
409}
410
411fn pair(p: [f32; 2]) -> Json {
412    json!([p[0], p[1]])
413}
414
415fn read_pair(v: &Json) -> Option<[f32; 2]> {
416    Some([v.get(0)?.as_f64()? as f32, v.get(1)?.as_f64()? as f32])
417}
418
419fn edges_json(edges: &[Edge]) -> Json {
420    Json::Array(edges.iter().map(Edge::to_json).collect())
421}
422
423fn read_edges(v: Option<&Json>) -> Option<Vec<Edge>> {
424    match v {
425        None | Some(Json::Null) => Some(Vec::new()),
426        Some(v) => v.as_array()?.iter().map(Edge::from_json).collect(),
427    }
428}
429
430fn read_strings(v: &Json) -> Option<Vec<String>> {
431    v.as_array()?
432        .iter()
433        .map(|s| s.as_str().map(str::to_string))
434        .collect()
435}
436
437impl Edit {
438    /// Its name in steps and commands: `connect`, `disconnect`, `move`,
439    /// `delete`, `add`, `param`.
440    pub fn kind(&self) -> &'static str {
441        match self {
442            Edit::Connect { .. } => "connect",
443            Edit::Disconnect { .. } => "disconnect",
444            Edit::Move { .. } => "move",
445            Edit::Delete { .. } => "delete",
446            Edit::Add { .. } => "add",
447            Edit::Param { .. } => "param",
448        }
449    }
450
451    /// Every edit but a slider's drag frames is a finished gesture.
452    pub fn done(&self) -> bool {
453        match self {
454            Edit::Param { done, .. } => *done,
455            _ => true,
456        }
457    }
458
459    /// Its fields as a JSON object (a step's arguments).
460    pub fn to_json(&self) -> Json {
461        match self {
462            Edit::Connect { from, to, replaces } => json!({
463                "from": from.to_json(),
464                "to": to.to_json(),
465                "replaces": edges_json(replaces),
466            }),
467            Edit::Disconnect { edges } => json!({ "edges": edges_json(edges) }),
468            Edit::Move { moves } => json!({
469                "moves": moves
470                    .iter()
471                    .map(|m| json!({ "node": m.node, "from": pair(m.from), "to": pair(m.to) }))
472                    .collect::<Vec<_>>(),
473            }),
474            Edit::Delete { nodes, edges } => json!({
475                "nodes": nodes,
476                "edges": edges_json(edges),
477            }),
478            Edit::Add { nodes } => json!({
479                "nodes": nodes
480                    .iter()
481                    .map(|n| json!({ "kind": n.kind, "at": pair(n.at), "copy_of": n.copy_of }))
482                    .collect::<Vec<_>>(),
483            }),
484            Edit::Param {
485                node,
486                param,
487                from,
488                to,
489                done,
490            } => json!({
491                "node": node,
492                "param": param,
493                "from": from,
494                "to": to,
495                "done": done,
496            }),
497        }
498    }
499
500    /// An edit of `kind` read back from its fields (a redirect, a
501    /// command's arguments); `None` when they do not make one.
502    pub fn from_json(kind: &str, v: &Json) -> Option<Edit> {
503        Some(match kind {
504            "connect" => Edit::Connect {
505                from: PortRef::from_json(v.get("from")?)?,
506                to: PortRef::from_json(v.get("to")?)?,
507                replaces: read_edges(v.get("replaces"))?,
508            },
509            "disconnect" => Edit::Disconnect {
510                edges: read_edges(Some(v.get("edges")?))?,
511            },
512            "move" => Edit::Move {
513                moves: v
514                    .get("moves")?
515                    .as_array()?
516                    .iter()
517                    .map(|m| {
518                        let to = read_pair(m.get("to")?)?;
519                        Some(Moved {
520                            node: m.get("node")?.as_str()?.to_string(),
521                            from: m.get("from").and_then(read_pair).unwrap_or(to),
522                            to,
523                        })
524                    })
525                    .collect::<Option<_>>()?,
526            },
527            "delete" => Edit::Delete {
528                nodes: read_strings(v.get("nodes")?)?,
529                edges: read_edges(v.get("edges"))?,
530            },
531            "add" => Edit::Add {
532                nodes: v
533                    .get("nodes")?
534                    .as_array()?
535                    .iter()
536                    .map(|n| {
537                        Some(NewNode {
538                            kind: n.get("kind")?.as_str()?.to_string(),
539                            at: n.get("at").and_then(read_pair).unwrap_or([0.0, 0.0]),
540                            copy_of: n.get("copy_of").and_then(Json::as_str).map(str::to_string),
541                        })
542                    })
543                    .collect::<Option<_>>()?,
544            },
545            "param" => Edit::Param {
546                node: v.get("node")?.as_str()?.to_string(),
547                param: v.get("param")?.as_str()?.to_string(),
548                from: v.get("from")?.as_f64()?,
549                to: v.get("to")?.as_f64()?,
550                done: v.get("done").and_then(Json::as_bool).unwrap_or(true),
551            },
552            _ => return None,
553        })
554    }
555}
556
557/// How much the editor shows, from the zoom.
558#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
559pub enum Level {
560    /// Zoomed out: compact nodes with their titles, groups folded into
561    /// stacks, wires between nodes.
562    Overview,
563    /// Nodes with their ports, wires between ports.
564    Ports,
565    /// Zoomed in: also the parameters, edited inline.
566    Detail,
567}
568
569impl Level {
570    pub fn name(self) -> &'static str {
571        match self {
572            Level::Overview => "overview",
573            Level::Ports => "ports",
574            Level::Detail => "detail",
575        }
576    }
577}
578
579/// What the editor reports besides edits.
580#[non_exhaustive]
581#[derive(Clone, Debug, PartialEq)]
582pub enum GraphEvent {
583    /// The selected nodes changed (now these).
584    Selection(Vec<String>),
585    /// The selected wires changed (now these).
586    WireSelection(Vec<Edge>),
587    /// The zoom crossed into another level.
588    Level(Level),
589    /// A wire was refused before any edit: the ports' types differ, the
590    /// node would feed itself, or the application said no.
591    Refused {
592        from: PortRef,
593        to: PortRef,
594        reason: String,
595    },
596}
597
598/// What an application (or an agent, through a command) asks of the
599/// editor, done at its next frame as if the user had done it.
600#[non_exhaustive]
601#[derive(Clone, Debug, PartialEq)]
602pub enum Request {
603    /// Propose an edit: a connection is type-checked, then the edit goes
604    /// through the hook like the user's.
605    Edit(Edit),
606    /// Select these nodes (the wires selected stay).
607    Select(Vec<String>),
608    /// Select these wires (the nodes selected stay).
609    SelectWires(Vec<Edge>),
610    /// Fit the whole graph in view.
611    Fit,
612    /// Zoom to show a level around the view's centre.
613    Level(Level),
614    /// Give a node the keyboard focus (and bring it into view).
615    Focus(String),
616}
617
618#[cfg(test)]
619mod tests {
620    use super::*;
621
622    fn p(n: &str, q: &str) -> PortRef {
623        PortRef::new(n, q)
624    }
625
626    #[test]
627    fn edits_round_trip_through_json() {
628        let edits = [
629            Edit::Connect {
630                from: p("load", "image"),
631                to: p("blur", "image"),
632                replaces: vec![Edge::new(p("old", "image"), p("blur", "image"))],
633            },
634            Edit::Disconnect {
635                edges: vec![Edge::new(p("a", "out"), p("b", "in"))],
636            },
637            Edit::Move {
638                moves: vec![Moved {
639                    node: "a".into(),
640                    from: [10.0, 20.5],
641                    to: [40.0, -3.25],
642                }],
643            },
644            Edit::Delete {
645                nodes: vec!["a".into()],
646                edges: vec![Edge::new(p("a", "out"), p("b", "in"))],
647            },
648            Edit::Add {
649                nodes: vec![NewNode {
650                    kind: "blur".into(),
651                    at: [1.0, 2.0],
652                    copy_of: Some("blur-1".into()),
653                }],
654            },
655            Edit::Param {
656                node: "blur".into(),
657                param: "radius".into(),
658                from: 1.0,
659                to: 2.5,
660                done: true,
661            },
662        ];
663        for e in edits {
664            assert_eq!(Edit::from_json(e.kind(), &e.to_json()), Some(e.clone()));
665        }
666        assert_eq!(Edit::from_json("connect", &json!({})), None);
667        assert_eq!(Edit::from_json("nothing", &json!({})), None);
668    }
669
670    #[test]
671    fn the_default_check_wants_one_type_and_two_nodes() {
672        let img = PortType::new("image");
673        let mask = PortType::new("mask");
674        let a = Node::new("a", "k", "A", [0.0, 0.0]);
675        let b = Node::new("b", "k", "B", [0.0, 0.0]);
676        let out = Port::new("out", "Out", img.clone());
677        let input = Port::new("in", "In", img);
678        let m = Port::new("m", "Mask", mask);
679        assert_eq!(check((&a, &out), (&b, &input)), Ok(()));
680        assert_eq!(check((&a, &out), (&a, &input)), Err(Refusal::SameNode));
681        assert!(matches!(
682            check((&a, &out), (&b, &m)),
683            Err(Refusal::Types { .. })
684        ));
685        // A type's colour is stable.
686        assert_eq!(PortType::new("image").color, PortType::new("image").color);
687    }
688}