1use std::ops::RangeInclusive;
10
11use serde_json::{Value as Json, json};
12
13#[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 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#[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 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 pub fn touches(&self, node: &str) -> bool {
67 self.from.node == node || self.to.node == node
68 }
69}
70
71pub 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#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct PortType {
86 pub name: String,
87 pub color: String,
90}
91
92impl PortType {
93 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 pub fn color(mut self, token: impl Into<String>) -> PortType {
106 self.color = token.into();
107 self
108 }
109}
110
111#[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#[derive(Clone, Debug, PartialEq)]
129pub struct Port {
130 pub id: String,
131 pub label: String,
132 pub ty: PortType,
133 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 pub fn multiple(mut self) -> Port {
151 self.multiple = true;
152 self
153 }
154}
155
156#[derive(Clone, Debug, PartialEq)]
158pub struct Node {
159 pub id: String,
160 pub kind: String,
163 pub title: String,
164 pub pos: [f32; 2],
166 pub inputs: Vec<Port>,
167 pub outputs: Vec<Port>,
168 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 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#[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#[derive(Clone, Debug, PartialEq)]
235pub struct Param {
236 pub id: String,
237 pub label: String,
238 pub value: f64,
239 pub range: RangeInclusive<f64>,
241 pub step: Option<f64>,
243 pub unit: Option<String>,
244 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#[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#[derive(Clone, Debug, PartialEq)]
300pub enum Refusal {
301 Types { from: String, to: String },
303 SameNode,
305 SameSide,
307 Exists,
309 Other(String),
311}
312
313pub 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
328pub trait GraphModel {
332 fn nodes(&self) -> Vec<Node>;
334
335 fn edges(&self) -> Vec<Edge>;
337
338 fn groups(&self) -> Vec<Group> {
340 Vec::new()
341 }
342
343 fn params(&self, _node: &str) -> Vec<Param> {
345 Vec::new()
346 }
347
348 fn kinds(&self) -> Vec<Kind> {
350 Vec::new()
351 }
352
353 fn can_connect(&self, from: (&Node, &Port), to: (&Node, &Port)) -> Result<(), Refusal> {
356 check(from, to)
357 }
358}
359
360#[derive(Clone, Debug, PartialEq)]
362pub struct Moved {
363 pub node: String,
364 pub from: [f32; 2],
365 pub to: [f32; 2],
366}
367
368#[derive(Clone, Debug, PartialEq)]
370pub struct NewNode {
371 pub kind: String,
372 pub at: [f32; 2],
373 pub copy_of: Option<String>,
375}
376
377#[non_exhaustive]
379#[derive(Clone, Debug, PartialEq)]
380pub enum Edit {
381 Connect {
385 from: PortRef,
386 to: PortRef,
387 replaces: Vec<Edge>,
388 },
389 Disconnect { edges: Vec<Edge> },
391 Move { moves: Vec<Moved> },
393 Delete {
395 nodes: Vec<String>,
396 edges: Vec<Edge>,
397 },
398 Add { nodes: Vec<NewNode> },
400 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 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 pub fn done(&self) -> bool {
453 match self {
454 Edit::Param { done, .. } => *done,
455 _ => true,
456 }
457 }
458
459 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
559pub enum Level {
560 Overview,
563 Ports,
565 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#[non_exhaustive]
581#[derive(Clone, Debug, PartialEq)]
582pub enum GraphEvent {
583 Selection(Vec<String>),
585 WireSelection(Vec<Edge>),
587 Level(Level),
589 Refused {
592 from: PortRef,
593 to: PortRef,
594 reason: String,
595 },
596}
597
598#[non_exhaustive]
601#[derive(Clone, Debug, PartialEq)]
602pub enum Request {
603 Edit(Edit),
606 Select(Vec<String>),
608 SelectWires(Vec<Edge>),
610 Fit,
612 Level(Level),
614 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 assert_eq!(PortType::new("image").color, PortType::new("image").color);
687 }
688}