matrix_sdk_ui/spaces/
graph.rs1use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque};
16
17use ruma::{OwnedRoomId, RoomId};
18
19#[derive(Debug)]
20struct SpaceGraphNode {
21 id: OwnedRoomId,
22 parents: BTreeSet<OwnedRoomId>,
23 children: BTreeSet<OwnedRoomId>,
24}
25
26impl SpaceGraphNode {
27 fn new(id: OwnedRoomId) -> Self {
28 Self { id, parents: BTreeSet::new(), children: BTreeSet::new() }
29 }
30}
31
32#[derive(Debug)]
36pub(super) struct SpaceGraph {
37 nodes: BTreeMap<OwnedRoomId, SpaceGraphNode>,
38}
39
40impl Default for SpaceGraph {
41 fn default() -> Self {
42 Self::new()
43 }
44}
45
46impl SpaceGraph {
47 pub(super) fn new() -> Self {
49 Self { nodes: BTreeMap::new() }
50 }
51
52 pub(super) fn root_nodes(&self) -> Vec<&RoomId> {
55 self.nodes
56 .values()
57 .filter(|node| node.parents.is_empty())
58 .map(|node| node.id.as_ref())
59 .collect()
60 }
61
62 pub(super) fn children_of(&self, node_id: &RoomId) -> Vec<&RoomId> {
65 self.nodes
66 .get(node_id)
67 .map_or(vec![], |node| node.children.iter().map(|id| id.as_ref()).collect())
68 }
69
70 pub(super) fn parents_of(&self, node_id: &RoomId) -> Vec<&RoomId> {
73 self.nodes
74 .get(node_id)
75 .map_or(vec![], |node| node.parents.iter().map(|id| id.as_ref()).collect())
76 }
77
78 pub(super) fn add_node(&mut self, node_id: OwnedRoomId) {
80 self.nodes.entry(node_id.clone()).or_insert(SpaceGraphNode::new(node_id));
81 }
82
83 pub(super) fn has_node(&self, node_id: &RoomId) -> bool {
85 self.nodes.contains_key(node_id)
86 }
87
88 pub(super) fn ancestors_of(&self, node_id: &RoomId) -> Vec<OwnedRoomId> {
91 let mut queue = VecDeque::from([node_id.to_owned()]);
92 let mut visited = HashSet::from([node_id.to_owned()]);
93 let mut ancestors = Vec::new();
94 while let Some(current) = queue.pop_front() {
95 for parent in self.parents_of(¤t) {
96 if visited.insert(parent.to_owned()) {
97 ancestors.push(parent.to_owned());
98 queue.push_back(parent.to_owned());
99 }
100 }
101 }
102 ancestors
103 }
104
105 pub(super) fn add_edge(&mut self, parent_id: OwnedRoomId, child_id: OwnedRoomId) {
108 let parent_entry =
109 self.nodes.entry(parent_id.clone()).or_insert(SpaceGraphNode::new(parent_id.clone()));
110 parent_entry.children.insert(child_id.clone());
111
112 let child_entry =
113 self.nodes.entry(child_id.clone()).or_insert(SpaceGraphNode::new(child_id));
114 child_entry.parents.insert(parent_id);
115 }
116
117 pub(super) fn flattened_bottom_up_subtree(&self, node_id: &RoomId) -> Vec<OwnedRoomId> {
122 if !self.has_node(node_id) {
123 return Vec::new();
124 }
125
126 let mut stack = vec![node_id.to_owned()];
127 let mut result = Vec::new();
128
129 while let Some(node) = stack.pop() {
130 result.insert(0, node.clone());
131
132 if let Some(node) = self.nodes.get(&node) {
133 for child in &node.children {
134 stack.push(child.to_owned());
135 }
136 }
137 }
138
139 result
140 }
141
142 pub(super) fn remove_cycles(&mut self) {
146 let mut visited = BTreeSet::new();
147 let mut stack = BTreeSet::new();
148
149 let mut edges_to_remove = Vec::new();
150
151 for node_id in self.nodes.keys() {
152 self.dfs_remove_cycles(node_id, &mut visited, &mut stack, &mut edges_to_remove);
153 }
154
155 for (parent, child) in edges_to_remove {
156 if let Some(node) = self.nodes.get_mut(&parent) {
157 node.children.remove(&child);
158 }
159 if let Some(node) = self.nodes.get_mut(&child) {
160 node.parents.remove(&parent);
161 }
162 }
163 }
164
165 fn dfs_remove_cycles(
166 &self,
167 node_id: &OwnedRoomId,
168 visited: &mut BTreeSet<OwnedRoomId>,
169 stack: &mut BTreeSet<OwnedRoomId>,
170 edges_to_remove: &mut Vec<(OwnedRoomId, OwnedRoomId)>,
171 ) {
172 if !visited.insert(node_id.clone()) {
173 return;
174 }
175
176 stack.insert(node_id.clone());
177
178 if let Some(node) = self.nodes.get(node_id) {
179 for child in &node.children {
180 if stack.contains(child) {
181 edges_to_remove.push((node_id.clone(), child.clone()));
183 } else {
184 self.dfs_remove_cycles(child, visited, stack, edges_to_remove);
185 }
186 }
187 }
188
189 stack.remove(node_id);
190 }
191}
192
193#[cfg(test)]
194mod tests {
195 use ruma::{owned_room_id, room_id};
196
197 use super::*;
198
199 #[test]
200 fn test_add_edge_and_root_nodes() {
201 let mut graph = SpaceGraph::new();
202
203 let a = owned_room_id!("!a:example.org");
204 let b = owned_room_id!("!b:example.org");
205 let c = owned_room_id!("!c:example.org");
206
207 graph.add_edge(a.clone(), b.clone());
208 graph.add_edge(a.clone(), c.clone());
209
210 assert_eq!(graph.root_nodes(), vec![&a]);
211
212 assert_eq!(graph.parents_of(&b), vec![&a]);
213 assert_eq!(graph.parents_of(&c), vec![&a]);
214
215 assert_eq!(graph.children_of(&a), vec![&b, &c]);
216 }
217
218 #[test]
219 fn test_remove_cycles() {
220 let mut graph = SpaceGraph::new();
221
222 let a = owned_room_id!("!a:example.org");
223 let b = owned_room_id!("!b:example.org");
224 let c = owned_room_id!("!c:example.org");
225
226 graph.add_edge(a.clone(), b.clone());
227 graph.add_edge(b, c.clone());
228 graph.add_edge(c.clone(), a.clone()); assert!(graph.nodes[&c].children.contains(&a));
231
232 graph.remove_cycles();
233
234 assert!(!graph.nodes[&c].children.contains(&a));
235 assert!(!graph.nodes[&a].parents.contains(&c));
236 }
237
238 #[test]
239 fn test_disconnected_graph_roots() {
240 let mut graph = SpaceGraph::new();
241
242 let a = owned_room_id!("!a:example.org");
243 let b = owned_room_id!("!b:example.org");
244 graph.add_edge(a.clone(), b);
245
246 let x = owned_room_id!("!x:example.org");
247 let y = owned_room_id!("!y:example.org");
248 graph.add_edge(x.clone(), y);
249
250 let mut roots = graph.root_nodes();
251 roots.sort_by_key(|key| key.to_string());
252
253 let expected: Vec<&OwnedRoomId> = vec![&a, &x];
254 assert_eq!(roots, expected);
255 }
256
257 #[test]
258 fn test_multiple_parents() {
259 let mut graph = SpaceGraph::new();
260
261 let a = owned_room_id!("!a:example.org");
262 let b = owned_room_id!("!b:example.org");
263 let c = owned_room_id!("!c:example.org");
264 let d = owned_room_id!("!d:example.org");
265
266 graph.add_edge(a.clone(), c.clone());
267 graph.add_edge(b.clone(), c.clone());
268 graph.add_edge(c.clone(), d);
269
270 let mut roots = graph.root_nodes();
271 roots.sort_by_key(|key| key.to_string());
272
273 let expected = vec![&a, &b];
274 assert_eq!(roots, expected);
275
276 let c_parents = &graph.nodes[&c].parents;
277 assert!(c_parents.contains(&a));
278 assert!(c_parents.contains(&b));
279 }
280
281 #[test]
282 fn test_flattened_bottom_up_subtree() {
283 let graph = vehicle_graph();
284
285 let children = graph.flattened_bottom_up_subtree(room_id!("!personal:x.y"));
286 let expected = vec![
287 owned_room_id!("!gravel:x.y"),
288 owned_room_id!("!mountain:x.y"),
289 owned_room_id!("!road:x.y"),
290 owned_room_id!("!bicycle:x.y"),
291 owned_room_id!("!car:x.y"),
292 owned_room_id!("!helicopter:x.y"),
293 owned_room_id!("!personal:x.y"),
294 ];
295
296 assert_eq!(children, expected);
297
298 let children = graph.flattened_bottom_up_subtree(room_id!("!shared:x.y"));
299 let expected = vec![
300 owned_room_id!("!bus:x.y"),
301 owned_room_id!("!train:x.y"),
302 owned_room_id!("!shared:x.y"),
303 ];
304
305 assert_eq!(children, expected);
306
307 let children = graph.flattened_bottom_up_subtree(room_id!("!plane:x.y"));
308 let expected = vec![owned_room_id!("!plane:x.y")];
309
310 assert_eq!(children, expected);
311
312 let children = graph.flattened_bottom_up_subtree(room_id!("!floo_powder:x.y"));
313 assert!(children.is_empty());
314 }
315
316 fn vehicle_graph() -> SpaceGraph {
317 let mut graph = SpaceGraph::new();
332
333 graph.add_edge(owned_room_id!("!vehicles:x.y"), owned_room_id!("!shared:x.y"));
334 graph.add_edge(owned_room_id!("!shared:x.y"), owned_room_id!("!bus:x.y"));
335 graph.add_edge(owned_room_id!("!shared:x.y"), owned_room_id!("!train:x.y"));
336
337 graph.add_edge(owned_room_id!("!vehicles:x.y"), owned_room_id!("!personal:x.y"));
338 graph.add_edge(owned_room_id!("!personal:x.y"), owned_room_id!("!car:x.y"));
339
340 graph.add_edge(owned_room_id!("!personal:x.y"), owned_room_id!("!bicycle:x.y"));
341 graph.add_edge(owned_room_id!("!bicycle:x.y"), owned_room_id!("!road:x.y"));
342 graph.add_edge(owned_room_id!("!bicycle:x.y"), owned_room_id!("!gravel:x.y"));
343 graph.add_edge(owned_room_id!("!bicycle:x.y"), owned_room_id!("!mountain:x.y"));
344
345 graph.add_edge(owned_room_id!("!personal:x.y"), owned_room_id!("!helicopter:x.y"));
346
347 graph.add_edge(owned_room_id!("!vehicles:x.y"), owned_room_id!("!cargo:x.y"));
348 graph.add_edge(owned_room_id!("!cargo:x.y"), owned_room_id!("!plane:x.y"));
349
350 graph
351 }
352}