canvas.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. from math import sqrt
  2. from PyQt4.QtGui import *
  3. from PyQt4.QtCore import *
  4. from shape import Shape
  5. class Canvas(QWidget):
  6. zoomRequest = pyqtSignal(int)
  7. scrollRequest = pyqtSignal(int, int)
  8. epsilon = 9.0 # TODO: Tune value
  9. def __init__(self, *args, **kwargs):
  10. super(Canvas, self).__init__(*args, **kwargs)
  11. self.shapes = []
  12. self.current = None
  13. self.line_color = QColor(0, 0, 255)
  14. self.line = Shape(line_color=self.line_color)
  15. self.scale = 1.0
  16. self.pixmap = None
  17. self.setFocusPolicy(Qt.WheelFocus)
  18. def mouseMoveEvent(self, ev):
  19. """Update line with last point and current coordinates."""
  20. # Don't allow the user to draw outside the image area.
  21. # FIXME: When making fast mouse movements, there is not enough
  22. # spatial resolution to leave the cursor at the edge of the
  23. # picture. We should probably place the line at the projected
  24. # position here...
  25. pos = self.transformPos(ev.posF())
  26. if self.outOfPixmap(pos):
  27. return ev.ignore()
  28. if self.current:
  29. if len(self.current) > 1 and self.closeEnough(pos, self.current[0]):
  30. self.line[1] = self.current[0]
  31. self.line.line_color = self.current.line_color
  32. else:
  33. self.line[1] = pos
  34. self.line.line_color = self.line_color
  35. self.repaint()
  36. def mousePressEvent(self, ev):
  37. if ev.button() == 1:
  38. if self.current:
  39. self.current.addPoint(self.line[1])
  40. self.line[0] = self.current[-1]
  41. if self.current.isClosed():
  42. self.finalise()
  43. self.repaint()
  44. else:
  45. pos = self.transformPos(ev.posF())
  46. self.current = Shape()
  47. self.line.points = [pos, pos]
  48. self.current.addPoint(pos)
  49. self.setMouseTracking(True)
  50. def mouseDoubleClickEvent(self, ev):
  51. if self.current:
  52. # Add first point in the list so that it is consistent
  53. # with shapes created the normal way.
  54. self.current.addPoint(self.current[0])
  55. self.finalise()
  56. def paintEvent(self, event):
  57. if not self.pixmap:
  58. return super(Canvas, self).paintEvent(event)
  59. p = QPainter()
  60. p.begin(self)
  61. p.setRenderHint(QPainter.Antialiasing)
  62. p.scale(self.scale, self.scale)
  63. p.translate(self.offsetToCenter())
  64. p.drawPixmap(0, 0, self.pixmap)
  65. for shape in self.shapes:
  66. shape.paint(p)
  67. if self.current:
  68. self.current.paint(p)
  69. self.line.paint(p)
  70. p.end()
  71. def transformPos(self, point):
  72. """Convert from widget-logical coordinates to painter-logical coordinates."""
  73. return point / self.scale - self.offsetToCenter()
  74. def offsetToCenter(self):
  75. s = self.scale
  76. area = super(Canvas, self).size()
  77. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  78. aw, ah = area.width(), area.height()
  79. x = (aw-w)/(2*s) if aw > w else 0
  80. y = (ah-h)/(2*s) if ah > h else 0
  81. return QPointF(x, y)
  82. def outOfPixmap(self, p):
  83. w, h = self.pixmap.width(), self.pixmap.height()
  84. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  85. def finalise(self):
  86. assert self.current
  87. self.current.fill = True
  88. self.shapes.append(self.current)
  89. self.current = None
  90. # TODO: Mouse tracking is still useful for selecting shapes!
  91. self.setMouseTracking(False)
  92. self.repaint()
  93. def closeEnough(self, p1, p2):
  94. #d = distance(p1 - p2)
  95. #m = (p1-p2).manhattanLength()
  96. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  97. return distance(p1 - p2) < self.epsilon
  98. # These two, along with a call to adjustSize are required for the
  99. # scroll area.
  100. def sizeHint(self):
  101. return self.minimumSizeHint()
  102. def minimumSizeHint(self):
  103. if self.pixmap:
  104. return self.scale * self.pixmap.size()
  105. return super(Canvas, self).minimumSizeHint()
  106. def wheelEvent(self, ev):
  107. if ev.orientation() == Qt.Vertical:
  108. mods = ev.modifiers()
  109. if Qt.ControlModifier == int(mods):
  110. self.zoomRequest.emit(ev.delta())
  111. else:
  112. self.scrollRequest.emit(ev.delta(),
  113. Qt.Horizontal if (Qt.ShiftModifier == int(mods))\
  114. else Qt.Vertical)
  115. else:
  116. self.scrollRequest.emit(ev.delta(), Qt.Horizontal)
  117. ev.accept()
  118. def keyPressEvent(self, ev):
  119. if ev.key() == Qt.Key_Escape and self.current:
  120. self.current = None
  121. self.setMouseTracking(False)
  122. self.repaint()
  123. def distance(p):
  124. return sqrt(p.x() * p.x() + p.y() * p.y())