tuikit/core/coords.py
changeset 91 de80e140b0ec
parent 87 ee5ea9671f28
child 94 e50dae408fe9
--- a/tuikit/core/coords.py	Wed Mar 19 20:42:52 2014 +0100
+++ b/tuikit/core/coords.py	Wed Mar 26 09:08:10 2014 +0100
@@ -104,3 +104,43 @@
 
     def __repr__(self):
         return 'ReadonlySize(w={0.w},h={0.h})'.format(self._size)
+
+
+class Rect:
+
+    """Rectangle is defined by coordinates and size."""
+
+    def __init__(self, x=0, y=0, w=0, h=0):
+        self.x = x
+        self.y = y
+        self.w = w
+        self.h = h
+
+    def __repr__(self):
+        return 'Rect(x={0.x},y={0.y},w={0.w},h={0.h})'.format(self)
+
+    def __contains__(self, point):
+        """Test if point is positioned inside rectangle.
+
+        `point` should be either Point or pair of int values.
+
+        """
+        x, y = point
+        return (self.x <= x < self.x + self.w
+            and self.y <= y < self.y + self.h)
+
+    def intersect(self, other):
+        x1 = max(self.x, other.x)
+        y1 = max(self.y, other.y)
+        x2 = min(self.x + self.w, other.x + other.w)
+        y2 = min(self.y + self.h, other.y + other.h)
+        if x1 >= x2 or y1 >= y2:
+            return Rect()
+        return Rect(x1, y1, x2-x1, y2-y1)
+
+    def union(self, other):
+        x = min(self.x, other.x)
+        y = min(self.y, other.y)
+        w = max(self.x + self.w, other.x + other.w) - x
+        h = max(self.y + self.h, other.y + other.h) - y
+        return Rect(x, y, w, h)