Skip to content

GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.

feat(domain): add `ContainerService` method for getting the lowest common ancestor of 2 containers

Lars Bergerde6fca06226c
diff --git a/GlazeWM.Domain/Containers/ContainerService.cs b/GlazeWM.Domain/Containers/ContainerService.cs
index a09c771f..ea09c618 100644
--- a/GlazeWM.Domain/Containers/ContainerService.cs
+++ b/GlazeWM.Domain/Containers/ContainerService.cs
@@ -1,4 +1,5 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
using System.Linq;
using GlazeWM.Domain.Common.Enums;
using GlazeWM.Domain.UserConfigs;
@@ -139,5 +140,33 @@ namespace GlazeWM.Domain.Containers
else
return GetDescendantInDirection(originContainer.Children.Last(), direction);
}
+
+ /// <summary>
+ /// Get the lowest container in the tree that has both `containerA` and `containerB` as
+ /// descendants.
+ /// </summary>
+ public Container GetLowestCommonAncestor(Container containerA, Container containerB)
+ {
+ var ancestorA = containerA;
+
+ // Traverse upwards from container A.
+ while (ancestorA != null)
+ {
+ var ancestorB = containerB;
+
+ // Traverse upwards from container B.
+ while (ancestorB != null)
+ {
+ if (ancestorA == ancestorB)
+ return ancestorA;
+
+ ancestorB = ancestorB.Parent;
+ }
+
+ ancestorA = ancestorA.Parent;
+ }
+
+ throw new Exception("No common ancestor between containers. This is a bug.");
+ }
}
}