1use crate::edge::Edge;
4use crate::geometry::{Rect, Size2, Vec2};
5use crate::ids::{EdgeId, NodeId, PortId};
6use crate::node::{Node, NodeStatus};
7use crate::port::{Port, PortDirection};
8use serde::{Deserialize, Serialize};
9use std::collections::{HashMap, HashSet, VecDeque};
10use std::fmt;
11
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub enum GraphError {
14 MissingNode(NodeId),
15 MissingPort(PortId),
16 MissingEdge(EdgeId),
17 DuplicateId(u64),
18 NodeInUse(NodeId),
20 PortInUse(PortId),
21 WouldCreateCycle {
22 parent: NodeId,
23 child: NodeId,
24 },
25 Format(String),
26}
27
28impl fmt::Display for GraphError {
29 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30 match self {
31 Self::MissingNode(id) => write!(f, "missing node {id}"),
32 Self::MissingPort(id) => write!(f, "missing port {id}"),
33 Self::MissingEdge(id) => write!(f, "missing edge {id}"),
34 Self::DuplicateId(id) => write!(f, "duplicate id {id}"),
35 Self::NodeInUse(id) => write!(f, "node {id} still has edges or children"),
36 Self::PortInUse(id) => write!(f, "port {id} still has edges"),
37 Self::WouldCreateCycle { parent, child } => {
38 write!(f, "reparenting {child} under {parent} would create a cycle")
39 }
40 Self::Format(m) => write!(f, "invalid document: {m}"),
41 }
42 }
43}
44
45impl std::error::Error for GraphError {}
46
47#[derive(Clone, Debug, Default)]
48pub struct Graph {
49 pub(crate) nodes: HashMap<NodeId, Node>,
50 pub(crate) ports: HashMap<PortId, Port>,
51 pub(crate) edges: HashMap<EdgeId, Edge>,
52 pub(crate) order: Vec<NodeId>,
54 pub(crate) port_edges: HashMap<PortId, Vec<EdgeId>>,
55 pub(crate) children: HashMap<NodeId, Vec<NodeId>>,
56 next_id: u64,
57 revision: u64,
58}
59
60#[derive(Serialize, Deserialize)]
62struct GraphDoc {
63 version: u32,
64 next_id: u64,
65 nodes: Vec<Node>,
66 ports: Vec<Port>,
67 edges: Vec<Edge>,
68}
69
70impl Graph {
71 pub fn new() -> Self {
72 Self {
73 next_id: 1,
74 ..Default::default()
75 }
76 }
77
78 fn alloc(&mut self) -> u64 {
81 let id = self.next_id.max(1);
82 self.next_id = id + 1;
83 id
84 }
85
86 pub fn alloc_node_id(&mut self) -> NodeId {
87 NodeId(self.alloc())
88 }
89
90 pub fn alloc_port_id(&mut self) -> PortId {
91 PortId(self.alloc())
92 }
93
94 pub fn alloc_edge_id(&mut self) -> EdgeId {
95 EdgeId(self.alloc())
96 }
97
98 fn reserve(&mut self, raw: u64) {
99 if raw >= self.next_id {
100 self.next_id = raw + 1;
101 }
102 }
103
104 pub fn revision(&self) -> u64 {
106 self.revision
107 }
108
109 pub(crate) fn bump(&mut self) {
110 self.revision += 1;
111 }
112
113 pub fn node(&self, id: NodeId) -> Option<&Node> {
116 self.nodes.get(&id)
117 }
118
119 pub fn port(&self, id: PortId) -> Option<&Port> {
120 self.ports.get(&id)
121 }
122
123 pub fn edge(&self, id: EdgeId) -> Option<&Edge> {
124 self.edges.get(&id)
125 }
126
127 pub fn node_count(&self) -> usize {
128 self.nodes.len()
129 }
130
131 pub fn edge_count(&self) -> usize {
132 self.edges.len()
133 }
134
135 pub fn nodes(&self) -> impl Iterator<Item = &Node> {
137 self.order.iter().filter_map(|id| self.nodes.get(id))
138 }
139
140 pub fn node_ids(&self) -> &[NodeId] {
141 &self.order
142 }
143
144 pub fn edges(&self) -> impl Iterator<Item = &Edge> {
145 self.edges.values()
146 }
147
148 pub fn ports_of(&self, node: NodeId) -> impl Iterator<Item = &Port> {
149 self.nodes
150 .get(&node)
151 .into_iter()
152 .flat_map(|n| n.inputs.iter().chain(n.outputs.iter()))
153 .filter_map(|p| self.ports.get(p))
154 }
155
156 pub fn edges_of_port(&self, port: PortId) -> &[EdgeId] {
157 self.port_edges.get(&port).map(Vec::as_slice).unwrap_or(&[])
158 }
159
160 pub fn connected_edges(&self, node: NodeId) -> Vec<EdgeId> {
162 let mut out: Vec<EdgeId> = self
163 .ports_of(node)
164 .flat_map(|p| self.edges_of_port(p.id).iter().copied())
165 .collect();
166 out.sort();
167 out.dedup();
168 out
169 }
170
171 pub fn incomers(&self, node: NodeId) -> Vec<NodeId> {
173 self.neighbours(node, PortDirection::Input)
174 }
175
176 pub fn outgoers(&self, node: NodeId) -> Vec<NodeId> {
178 self.neighbours(node, PortDirection::Output)
179 }
180
181 fn neighbours(&self, node: NodeId, dir: PortDirection) -> Vec<NodeId> {
182 let mut out: Vec<NodeId> = self
183 .ports_of(node)
184 .filter(|p| p.direction == dir)
185 .flat_map(|p| self.edges_of_port(p.id))
186 .filter_map(|e| self.edges.get(e))
187 .filter_map(|e| {
188 let other = if dir == PortDirection::Input {
189 e.from
190 } else {
191 e.to
192 };
193 self.ports.get(&other).map(|p| p.node)
194 })
195 .collect();
196 out.sort();
197 out.dedup();
198 out
199 }
200
201 pub fn edge_nodes(&self, edge: &Edge) -> Option<(NodeId, NodeId)> {
203 Some((
204 self.ports.get(&edge.from)?.node,
205 self.ports.get(&edge.to)?.node,
206 ))
207 }
208
209 pub fn children_of(&self, parent: NodeId) -> &[NodeId] {
210 self.children.get(&parent).map(Vec::as_slice).unwrap_or(&[])
211 }
212
213 pub fn subtree(&self, root: NodeId) -> Vec<NodeId> {
215 let mut out = Vec::new();
216 let mut stack = vec![root];
217 while let Some(id) = stack.pop() {
218 if self.nodes.contains_key(&id) {
219 out.push(id);
220 stack.extend(self.children_of(id).iter().rev());
221 }
222 }
223 out
224 }
225
226 pub fn is_ancestor(&self, ancestor: NodeId, mut node: NodeId) -> bool {
227 while let Some(p) = self.nodes.get(&node).and_then(|n| n.parent) {
228 if p == ancestor {
229 return true;
230 }
231 node = p;
232 }
233 false
234 }
235
236 pub fn world_pos(&self, id: NodeId) -> Option<Vec2> {
238 let mut node = self.nodes.get(&id)?;
239 let mut pos = node.pos;
240 while let Some(p) = node.parent {
241 node = self.nodes.get(&p)?;
242 pos = pos.plus(node.pos);
243 }
244 Some(pos)
245 }
246
247 pub fn world_rect(&self, id: NodeId) -> Option<Rect> {
248 Some(Rect::from_origin_size(
249 self.world_pos(id)?,
250 self.nodes.get(&id)?.size,
251 ))
252 }
253
254 pub fn to_local(&self, world: Vec2, parent: Option<NodeId>) -> Option<Vec2> {
256 match parent {
257 None => Some(world),
258 Some(p) => Some(world.minus(self.world_pos(p)?)),
259 }
260 }
261
262 pub fn bounds(&self) -> Option<Rect> {
264 self.order
265 .iter()
266 .filter_map(|id| self.world_rect(*id))
267 .reduce(|a, b| a.union(b))
268 }
269
270 pub fn nodes_in_rect(&self, rect: &Rect, fully: bool) -> Vec<NodeId> {
272 self.order
273 .iter()
274 .copied()
275 .filter(|id| {
276 self.world_rect(*id).is_some_and(|r| {
277 if fully {
278 rect.contains_rect(&r)
279 } else {
280 rect.intersects(&r)
281 }
282 })
283 })
284 .collect()
285 }
286
287 pub fn node_at(&self, p: Vec2) -> Option<NodeId> {
289 self.order
290 .iter()
291 .rev()
292 .copied()
293 .find(|id| self.world_rect(*id).is_some_and(|r| r.contains(p)))
294 }
295
296 pub fn topo_order(&self) -> Result<Vec<NodeId>, NodeId> {
298 let mut indeg: HashMap<NodeId, usize> = self.order.iter().map(|id| (*id, 0)).collect();
299 let mut succ: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
300 for e in self.edges.values() {
301 if let Some((a, b)) = self.edge_nodes(e) {
302 succ.entry(a).or_default().push(b);
303 *indeg.entry(b).or_default() += 1;
304 }
305 }
306 let mut queue: VecDeque<NodeId> = self
307 .order
308 .iter()
309 .copied()
310 .filter(|id| indeg[id] == 0)
311 .collect();
312 let mut out = Vec::with_capacity(self.order.len());
313 while let Some(n) = queue.pop_front() {
314 out.push(n);
315 for m in succ.get(&n).into_iter().flatten() {
316 let d = indeg.get_mut(m).expect("indegree entry");
317 *d -= 1;
318 if *d == 0 {
319 queue.push_back(*m);
320 }
321 }
322 }
323 if out.len() == self.order.len() {
324 Ok(out)
325 } else {
326 let done: HashSet<NodeId> = out.into_iter().collect();
327 Err(*self
328 .order
329 .iter()
330 .find(|id| !done.contains(id))
331 .expect("cycle member"))
332 }
333 }
334
335 pub fn has_cycle(&self) -> bool {
336 self.topo_order().is_err()
337 }
338
339 pub fn would_create_cycle(&self, from: NodeId, to: NodeId) -> bool {
341 if from == to {
342 return true;
343 }
344 let mut seen = HashSet::new();
345 let mut stack = vec![to];
346 while let Some(n) = stack.pop() {
347 if n == from {
348 return true;
349 }
350 if seen.insert(n) {
351 stack.extend(self.outgoers(n));
352 }
353 }
354 false
355 }
356
357 pub fn set_status(&mut self, id: NodeId, status: NodeStatus) -> bool {
361 match self.nodes.get_mut(&id) {
362 Some(n) if n.status != status => {
363 n.status = status;
364 self.bump();
365 true
366 }
367 _ => false,
368 }
369 }
370
371 pub fn set_edge_state(&mut self, id: EdgeId, state: crate::edge::EdgeState) -> bool {
372 match self.edges.get_mut(&id) {
373 Some(e) if e.state != state => {
374 e.state = state;
375 self.bump();
376 true
377 }
378 _ => false,
379 }
380 }
381
382 pub fn bring_to_front(&mut self, id: NodeId) {
384 let tree = self.subtree(id);
385 let set: HashSet<NodeId> = tree.iter().copied().collect();
386 let mut moved: Vec<NodeId> = self
387 .order
388 .iter()
389 .copied()
390 .filter(|n| set.contains(n))
391 .collect();
392 self.order.retain(|n| !set.contains(n));
393 self.order.append(&mut moved);
394 self.bump();
395 }
396
397 pub(crate) fn insert_node(
400 &mut self,
401 mut node: Node,
402 ports: Vec<Port>,
403 ) -> Result<(), GraphError> {
404 if self.nodes.contains_key(&node.id) {
405 return Err(GraphError::DuplicateId(node.id.0));
406 }
407 if let Some(p) = node.parent
408 && !self.nodes.contains_key(&p)
409 {
410 return Err(GraphError::MissingNode(p));
411 }
412 for p in &ports {
413 if self.ports.contains_key(&p.id) {
414 return Err(GraphError::DuplicateId(p.id.0));
415 }
416 }
417 self.reserve(node.id.0);
418 node.inputs.clear();
419 node.outputs.clear();
420 for mut p in ports {
421 self.reserve(p.id.0);
422 p.node = node.id;
423 match p.direction {
424 PortDirection::Input => node.inputs.push(p.id),
425 PortDirection::Output => node.outputs.push(p.id),
426 }
427 self.ports.insert(p.id, p);
428 }
429 if let Some(p) = node.parent {
430 self.children.entry(p).or_default().push(node.id);
431 }
432 self.order.push(node.id);
433 self.nodes.insert(node.id, node);
434 self.bump();
435 Ok(())
436 }
437
438 pub(crate) fn take_node(&mut self, id: NodeId) -> Result<(Node, Vec<Port>), GraphError> {
439 if !self.nodes.contains_key(&id) {
440 return Err(GraphError::MissingNode(id));
441 }
442 if !self.children_of(id).is_empty() || !self.connected_edges(id).is_empty() {
443 return Err(GraphError::NodeInUse(id));
444 }
445 let node = self.nodes.remove(&id).expect("checked");
446 let ports = node
447 .inputs
448 .iter()
449 .chain(node.outputs.iter())
450 .filter_map(|p| {
451 self.port_edges.remove(p);
452 self.ports.remove(p)
453 })
454 .collect();
455 if let Some(p) = node.parent
456 && let Some(list) = self.children.get_mut(&p)
457 {
458 list.retain(|c| *c != id);
459 }
460 self.children.remove(&id);
461 self.order.retain(|n| *n != id);
462 self.bump();
463 Ok((node, ports))
464 }
465
466 pub(crate) fn insert_edge(&mut self, edge: Edge) -> Result<(), GraphError> {
467 if self.edges.contains_key(&edge.id) {
468 return Err(GraphError::DuplicateId(edge.id.0));
469 }
470 for p in [edge.from, edge.to] {
471 if !self.ports.contains_key(&p) {
472 return Err(GraphError::MissingPort(p));
473 }
474 }
475 self.reserve(edge.id.0);
476 self.port_edges.entry(edge.from).or_default().push(edge.id);
477 self.port_edges.entry(edge.to).or_default().push(edge.id);
478 self.edges.insert(edge.id, edge);
479 self.bump();
480 Ok(())
481 }
482
483 pub(crate) fn take_edge(&mut self, id: EdgeId) -> Result<Edge, GraphError> {
484 let edge = self.edges.remove(&id).ok_or(GraphError::MissingEdge(id))?;
485 for p in [edge.from, edge.to] {
486 if let Some(list) = self.port_edges.get_mut(&p) {
487 list.retain(|e| *e != id);
488 }
489 }
490 self.bump();
491 Ok(edge)
492 }
493
494 pub(crate) fn move_in_order(&mut self, id: NodeId, index: usize) {
495 if let Some(cur) = self.order.iter().position(|n| *n == id) {
496 self.order.remove(cur);
497 let i = index.min(self.order.len());
498 self.order.insert(i, id);
499 }
500 }
501
502 pub(crate) fn node_mut(&mut self, id: NodeId) -> Result<&mut Node, GraphError> {
503 self.nodes.get_mut(&id).ok_or(GraphError::MissingNode(id))
504 }
505
506 pub(crate) fn set_parent(
507 &mut self,
508 id: NodeId,
509 parent: Option<NodeId>,
510 ) -> Result<(), GraphError> {
511 if let Some(p) = parent {
512 if !self.nodes.contains_key(&p) {
513 return Err(GraphError::MissingNode(p));
514 }
515 if p == id || self.is_ancestor(id, p) {
516 return Err(GraphError::WouldCreateCycle {
517 parent: p,
518 child: id,
519 });
520 }
521 }
522 let old = self.node_mut(id)?.parent;
523 if let Some(o) = old
524 && let Some(list) = self.children.get_mut(&o)
525 {
526 list.retain(|c| *c != id);
527 }
528 if let Some(p) = parent {
529 self.children.entry(p).or_default().push(id);
530 }
531 self.node_mut(id)?.parent = parent;
532 Ok(())
533 }
534
535 pub fn add_node_with(
539 &mut self,
540 kind: &str,
541 pos: Vec2,
542 size: Size2,
543 inputs: usize,
544 outputs: usize,
545 ) -> (NodeId, Vec<PortId>, Vec<PortId>) {
546 let id = self.alloc_node_id();
547 let mut ports = Vec::new();
548 let mut ins = Vec::new();
549 let mut outs = Vec::new();
550 for _ in 0..inputs {
551 let pid = self.alloc_port_id();
552 ins.push(pid);
553 ports.push(Port::new(pid, id, PortDirection::Input));
554 }
555 for _ in 0..outputs {
556 let pid = self.alloc_port_id();
557 outs.push(pid);
558 ports.push(Port::new(pid, id, PortDirection::Output));
559 }
560 self.insert_node(Node::new(id, kind, pos, size), ports)
561 .expect("fresh ids");
562 (id, ins, outs)
563 }
564
565 pub fn connect(&mut self, from: PortId, to: PortId) -> Result<EdgeId, GraphError> {
567 let id = self.alloc_edge_id();
568 self.insert_edge(Edge::new(id, from, to))?;
569 Ok(id)
570 }
571
572 pub fn to_json(&self) -> serde_json::Value {
575 let mut edges: Vec<Edge> = self.edges.values().cloned().collect();
576 edges.sort_by_key(|e| e.id);
577 let mut ports: Vec<Port> = self.ports.values().cloned().collect();
578 ports.sort_by_key(|p| p.id);
579 let doc = GraphDoc {
580 version: crate::FORMAT_VERSION,
581 next_id: self.next_id,
582 nodes: self.nodes().cloned().collect(),
583 ports,
584 edges,
585 };
586 serde_json::to_value(doc).expect("graph is serialisable")
587 }
588
589 pub fn from_json(value: serde_json::Value) -> Result<Self, GraphError> {
590 let doc: GraphDoc =
591 serde_json::from_value(value).map_err(|e| GraphError::Format(e.to_string()))?;
592 if doc.version > crate::FORMAT_VERSION {
593 return Err(GraphError::Format(format!(
594 "unsupported version {}",
595 doc.version
596 )));
597 }
598 let mut g = Graph::new();
599 let mut ports_by_node: HashMap<NodeId, Vec<Port>> = HashMap::new();
600 for p in doc.ports {
601 ports_by_node.entry(p.node).or_default().push(p);
602 }
603 let parents: HashMap<NodeId, Option<NodeId>> =
606 doc.nodes.iter().map(|n| (n.id, n.parent)).collect();
607 let depth = |mut id: NodeId| {
608 let mut d = 0usize;
609 while let Some(Some(p)) = parents.get(&id) {
610 d += 1;
611 id = *p;
612 if d > parents.len() {
613 break;
614 }
615 }
616 d
617 };
618 let mut nodes = doc.nodes;
619 let order: Vec<NodeId> = nodes.iter().map(|n| n.id).collect();
620 nodes.sort_by_key(|n| depth(n.id));
621 for n in nodes {
622 let mut ports = ports_by_node.remove(&n.id).unwrap_or_default();
624 let rank: HashMap<PortId, usize> = n
625 .inputs
626 .iter()
627 .chain(n.outputs.iter())
628 .enumerate()
629 .map(|(i, p)| (*p, i))
630 .collect();
631 ports.sort_by_key(|p| rank.get(&p.id).copied().unwrap_or(usize::MAX));
632 g.insert_node(n, ports)?;
633 }
634 g.order = order;
635 for e in doc.edges {
636 g.insert_edge(e)?;
637 }
638 g.next_id = g.next_id.max(doc.next_id);
639 Ok(g)
640 }
641}
642
643#[cfg(test)]
644mod tests {
645 use super::*;
646
647 fn chain() -> (Graph, Vec<NodeId>) {
648 let mut g = Graph::new();
649 let sz = Size2::new(100.0, 40.0);
650 let (a, _, ao) = g.add_node_with("a", Vec2::new(0.0, 0.0), sz, 0, 1);
651 let (b, bi, bo) = g.add_node_with("b", Vec2::new(200.0, 0.0), sz, 1, 1);
652 let (c, ci, _) = g.add_node_with("c", Vec2::new(400.0, 0.0), sz, 1, 0);
653 g.connect(ao[0], bi[0]).unwrap();
654 g.connect(bo[0], ci[0]).unwrap();
655 (g, vec![a, b, c])
656 }
657
658 #[test]
659 fn neighbours_and_topology() {
660 let (g, n) = chain();
661 assert_eq!(g.incomers(n[1]), vec![n[0]]);
662 assert_eq!(g.outgoers(n[1]), vec![n[2]]);
663 assert_eq!(g.connected_edges(n[1]).len(), 2);
664 assert_eq!(g.topo_order().unwrap(), n);
665 assert!(g.would_create_cycle(n[2], n[0]));
666 assert!(!g.would_create_cycle(n[0], n[2]));
667 }
668
669 #[test]
670 fn nested_world_positions() {
671 let mut g = Graph::new();
672 let (group, _, _) = g.add_node_with(
673 "group",
674 Vec2::new(100.0, 50.0),
675 Size2::new(300.0, 200.0),
676 0,
677 0,
678 );
679 let (child, _, _) =
680 g.add_node_with("c", Vec2::new(10.0, 20.0), Size2::new(50.0, 20.0), 0, 0);
681 g.set_parent(child, Some(group)).unwrap();
682 assert_eq!(g.world_pos(child), Some(Vec2::new(110.0, 70.0)));
683 assert_eq!(g.children_of(group), &[child]);
684 assert_eq!(
685 g.set_parent(group, Some(child)),
686 Err(GraphError::WouldCreateCycle {
687 parent: child,
688 child: group
689 })
690 );
691 assert_eq!(g.node_at(Vec2::new(115.0, 75.0)), Some(child));
692 }
693
694 #[test]
695 fn remove_requires_detached() {
696 let (mut g, n) = chain();
697 assert_eq!(g.take_node(n[1]).unwrap_err(), GraphError::NodeInUse(n[1]));
698 }
699
700 #[test]
701 fn json_round_trip() {
702 let (mut g, n) = chain();
703 g.set_parent(n[2], Some(n[1])).unwrap();
704 let json = g.to_json();
705 let back = Graph::from_json(json.clone()).unwrap();
706 assert_eq!(back.to_json(), json);
707 assert_eq!(back.topo_order().unwrap(), n);
708 assert_eq!(back.children_of(n[1]), &[n[2]]);
709 }
710
711 #[test]
712 fn rect_queries() {
713 let (g, n) = chain();
714 let r = Rect::from_corners(Vec2::new(-10.0, -10.0), Vec2::new(250.0, 50.0));
715 assert_eq!(g.nodes_in_rect(&r, false), vec![n[0], n[1]]);
716 assert_eq!(g.nodes_in_rect(&r, true), vec![n[0]]);
717 assert_eq!(g.bounds().unwrap().max, Vec2::new(500.0, 40.0));
718 }
719}