Added 'list_only' option (and modified 'run()' to respect it).
[python/dscho.git] / Lib / lib-stdwin / rect.py
blob393eafd7692da08424dad18ea8fcc5ddc354d48c
1 # Module 'rect'.
3 # Operations on rectangles.
4 # There is some normalization: all results return the object 'empty'
5 # if their result would contain no points.
8 # Exception.
10 error = 'rect.error'
13 # The empty rectangle.
15 empty = (0, 0), (0, 0)
18 # Check if a rectangle is empty.
20 def is_empty(r):
21 (left, top), (right, bottom) = r
22 return left >= right or top >= bottom
25 # Compute the intersection or two or more rectangles.
26 # This works with a list or tuple argument.
28 def intersect(list):
29 if not list: raise error, 'intersect called with empty list'
30 if is_empty(list[0]): return empty
31 (left, top), (right, bottom) = list[0]
32 for rect in list[1:]:
33 if is_empty(rect):
34 return empty
35 (l, t), (r, b) = rect
36 if left < l: left = l
37 if top < t: top = t
38 if right > r: right = r
39 if bottom > b: bottom = b
40 if is_empty(((left, top), (right, bottom))):
41 return empty
42 return (left, top), (right, bottom)
45 # Compute the smallest rectangle containing all given rectangles.
46 # This works with a list or tuple argument.
48 def union(list):
49 (left, top), (right, bottom) = list[0]
50 for (l, t), (r, b) in list[1:]:
51 if not is_empty(((l, t), (r, b))):
52 if l < left: left = l
53 if t < top: top = t
54 if r > right: right = r
55 if b > bottom: bottom = b
56 res = (left, top), (right, bottom)
57 if is_empty(res):
58 return empty
59 return res
62 # Check if a point is in a rectangle.
64 def pointinrect((h, v), ((left, top), (right, bottom))):
65 return left <= h < right and top <= v < bottom
68 # Return a rectangle that is dh, dv inside another
70 def inset(((left, top), (right, bottom)), (dh, dv)):
71 left = left + dh
72 top = top + dv
73 right = right - dh
74 bottom = bottom - dv
75 r = (left, top), (right, bottom)
76 if is_empty(r):
77 return empty
78 else:
79 return r
82 # Conversions between rectangles and 'geometry tuples',
83 # given as origin (h, v) and dimensions (width, height).
85 def rect2geom((left, top), (right, bottom)):
86 return (left, top), (right-left, bottom-top)
88 def geom2rect((h, v), (width, height)):
89 return (h, v), (h+width, v+height)