• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2015 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4"""Objects for convenient manipulation of points and other surface areas."""
5
6import collections
7
8
9class Point(collections.namedtuple('Point', ['x', 'y'])):
10  """Object to represent an (x, y) point on a surface.
11
12  Args:
13    x, y: Two numeric coordinates that define the point.
14  """
15  __slots__ = ()
16
17  def __str__(self):
18    """Get a useful string representation of the object."""
19    return '(%s, %s)' % (self.x, self.y)
20
21  def __add__(self, other):
22    """Sum of two points, e.g. p + q."""
23    if isinstance(other, Point):
24      return Point(self.x + other.x, self.y + other.y)
25    else:
26      return NotImplemented
27
28  def __mul__(self, factor):
29    """Multiplication on the right is not implemented."""
30    # This overrides the default behaviour of a tuple multiplied by a constant
31    # on the right, which does not make sense for a Point.
32    return NotImplemented
33
34  def __rmul__(self, factor):
35    """Multiply a point by a scalar factor on the left, e.g. 2 * p."""
36    return Point(factor * self.x, factor * self.y)
37
38
39class Rectangle(
40    collections.namedtuple('Rectangle', ['top_left', 'bottom_right'])):
41  """Object to represent a rectangle on a surface.
42
43  Args:
44    top_left: A pair of (left, top) coordinates. Might be given as a Point
45      or as a two-element sequence (list, tuple, etc.).
46    bottom_right: A pair (right, bottom) coordinates.
47  """
48  __slots__ = ()
49
50  def __new__(cls, top_left, bottom_right):
51    if not isinstance(top_left, Point):
52      top_left = Point(*top_left)
53    if not isinstance(bottom_right, Point):
54      bottom_right = Point(*bottom_right)
55    return super(Rectangle, cls).__new__(cls, top_left, bottom_right)
56
57  def __str__(self):
58    """Get a useful string representation of the object."""
59    return '[%s, %s]' % (self.top_left, self.bottom_right)
60
61  @property
62  def center(self):
63    """Get the point at the center of the rectangle."""
64    return 0.5 * (self.top_left + self.bottom_right)
65
66  @classmethod
67  def FromDict(cls, d):
68    """Create a rectangle object from a dictionary.
69
70    Args:
71      d: A dictionary (or mapping) of the form, e.g., {'top': 0, 'left': 0,
72         'bottom': 1, 'right': 1}.
73    """
74    return cls(Point(d['left'], d['top']), Point(d['right'], d['bottom']))
75