canvas.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. newShape = pyqtSignal(QPoint)
  9. SELECT, EDIT = range(2)
  10. epsilon = 9.0 # TODO: Tune value
  11. def __init__(self, *args, **kwargs):
  12. super(Canvas, self).__init__(*args, **kwargs)
  13. # Initialise local state.
  14. self.mode = self.SELECT
  15. self.shapes = []
  16. self.current = None
  17. self.selectedShape=None # save the selected shape here
  18. self.selectedShapeCopy=None
  19. self.lineColor = QColor(0, 0, 255)
  20. self.line = Shape(line_color=self.lineColor)
  21. self.mouseButtonIsPressed=False #when it is true and shape is selected , move the shape with the mouse move event
  22. self.prevPoint=QPoint()
  23. self.scale = 1.0
  24. self.pixmap = None
  25. # Set widget options.
  26. self.setMouseTracking(True)
  27. self.setFocusPolicy(Qt.WheelFocus)
  28. def editing(self):
  29. return self.mode == self.EDIT
  30. def setEditing(self, value=True):
  31. self.mode = self.EDIT if value else self.SELECT
  32. def mouseMoveEvent(self, ev):
  33. """Update line with last point and current coordinates."""
  34. if ev.button() == Qt.RightButton:
  35. if self.selectedShapeCopy:
  36. if self.prevPoint:
  37. point=QPoint(self.prevPoint)
  38. dx= ev.x()-point.x()
  39. dy=ev.y()-point.y()
  40. self.selectedShapeCopy.moveBy(dx,dy)
  41. self.repaint()
  42. self.prevPoint=ev.pos()
  43. elif self.selectedShape:
  44. newShape=Shape()
  45. for point in self.selectedShape.points:
  46. newShape.addPoint(point)
  47. self.selectedShapeCopy=newShape
  48. self.repaint()
  49. return
  50. # Polygon drawing.
  51. if self.current and self.editing():
  52. pos = self.transformPos(ev.posF())
  53. color = self.lineColor
  54. if self.outOfPixmap(pos):
  55. # Don't allow the user to draw outside the pixmap.
  56. # Project the point to the pixmap's edges.
  57. pos = self.intersectionPoint(pos)
  58. elif len(self.current) > 1 and self.closeEnough(pos, self.current[0]):
  59. # Attract line to starting point and colorise to alert the user:
  60. # TODO: I would also like to highlight the pixel somehow.
  61. pos = self.current[0]
  62. color = self.current.line_color
  63. self.line[1] = pos
  64. self.line.line_color = color
  65. self.repaint()
  66. return
  67. if self.selectedShape:
  68. if self.prevPoint:
  69. point=QPoint(self.prevPoint)
  70. # print point.x()
  71. dx= ev.x()-point.x()
  72. dy=ev.y()-point.y()
  73. self.selectedShape.moveBy(dx,dy)
  74. self.repaint()
  75. self.prevPoint=ev.pos()
  76. def mousePressEvent(self, ev):
  77. if ev.button() == Qt.LeftButton:
  78. if self.editing():
  79. if self.current:
  80. self.current.addPoint(self.line[1])
  81. self.line[0] = self.current[-1]
  82. if self.current.isClosed():
  83. self.finalise(ev)
  84. else:
  85. pos = self.transformPos(ev.posF())
  86. if self.outOfPixmap(pos):
  87. return
  88. self.current = Shape()
  89. self.line.points = [pos, pos]
  90. self.current.addPoint(pos)
  91. else:
  92. self.selectShape(ev.pos())
  93. self.prevPoint=ev.pos()
  94. self.repaint()
  95. def mouseDoubleClickEvent(self, ev):
  96. # FIXME: Don't create shape with 2 vertices only.
  97. if self.current and self.editing():
  98. # Add first point in the list so that it is consistent
  99. # with shapes created the normal way.
  100. self.current.addPoint(self.current[0])
  101. self.finalise(ev)
  102. def selectShape(self, point):
  103. """Select the first shape created which contains this point."""
  104. self.deSelectShape()
  105. for shape in self.shapes:
  106. if shape.containsPoint(point):
  107. shape.selected = True
  108. self.selectedShape = shape
  109. return self.repaint()
  110. def deSelectShape(self):
  111. if self.selectedShape:
  112. self.selectedShape.selected = False
  113. self.repaint()
  114. def deleteSelected(self):
  115. if self.selectedShape:
  116. self.shapes.remove(self.selectedShape)
  117. self.selectedShape=None
  118. #print self.selectedShape()
  119. self.repaint()
  120. def paintEvent(self, event):
  121. if not self.pixmap:
  122. return super(Canvas, self).paintEvent(event)
  123. p = QPainter()
  124. p.begin(self)
  125. p.setRenderHint(QPainter.Antialiasing)
  126. p.scale(self.scale, self.scale)
  127. p.translate(self.offsetToCenter())
  128. p.drawPixmap(0, 0, self.pixmap)
  129. Shape.scale = self.scale
  130. for shape in self.shapes:
  131. shape.paint(p)
  132. if self.current:
  133. self.current.paint(p)
  134. self.line.paint(p)
  135. if self.selectedShapeCopy:
  136. self.selectedShapeCopy.paint(p)
  137. p.end()
  138. def transformPos(self, point):
  139. """Convert from widget-logical coordinates to painter-logical coordinates."""
  140. return point / self.scale - self.offsetToCenter()
  141. def offsetToCenter(self):
  142. s = self.scale
  143. area = super(Canvas, self).size()
  144. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  145. aw, ah = area.width(), area.height()
  146. x = (aw-w)/(2*s) if aw > w else 0
  147. y = (ah-h)/(2*s) if ah > h else 0
  148. return QPointF(x, y)
  149. def outOfPixmap(self, p):
  150. w, h = self.pixmap.width(), self.pixmap.height()
  151. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  152. def finalise(self, ev):
  153. assert self.current
  154. self.current.fill = True
  155. self.shapes.append(self.current)
  156. self.current = None
  157. self.setEditing(False)
  158. self.repaint()
  159. self.newShape.emit(self.mapToGlobal(ev.pos()))
  160. def closeEnough(self, p1, p2):
  161. #d = distance(p1 - p2)
  162. #m = (p1-p2).manhattanLength()
  163. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  164. return distance(p1 - p2) < self.epsilon
  165. def intersectionPoint(self, mousePos):
  166. # Cycle through each image edge in clockwise fashion,
  167. # and find the one intersecting the current line segment.
  168. # http://paulbourke.net/geometry/lineline2d/
  169. size = self.pixmap.size()
  170. points = [(0,0),
  171. (size.width(), 0),
  172. (size.width(), size.height()),
  173. (0, size.height())]
  174. x1, y1 = self.current[-1].x(), self.current[-1].y()
  175. x2, y2 = mousePos.x(), mousePos.y()
  176. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  177. x3, y3 = points[i]
  178. x4, y4 = points[(i+1)%4]
  179. if (x, y) == (x1, y1):
  180. # Handle cases where previous point is on one of the edges.
  181. if x3 == x4:
  182. return QPointF(x3, min(max(0, y2), max(y3, y4)))
  183. else: # y3 == y4
  184. return QPointF(min(max(0, x2), max(x3, x4)), y3)
  185. return QPointF(x, y)
  186. def intersectingEdges(self, (x1, y1), (x2, y2), points):
  187. """For each edge formed by `points', yield the intersection
  188. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  189. Also return the distance of `(x2,y2)' to the middle of the
  190. edge along with its index, so that the one closest can be chosen."""
  191. for i in xrange(4):
  192. x3, y3 = points[i]
  193. x4, y4 = points[(i+1) % 4]
  194. denom = (y4-y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  195. nua = (x4-x3) * (y1-y3) - (y4-y3) * (x1-x3)
  196. nub = (x2-x1) * (y1-y3) - (y2-y1) * (x1-x3)
  197. if denom == 0:
  198. # This covers two cases:
  199. # nua == nub == 0: Coincident
  200. # otherwise: Parallel
  201. continue
  202. ua, ub = nua / denom, nub / denom
  203. if 0 <= ua <= 1 and 0 <= ub <= 1:
  204. x = x1 + ua * (x2 - x1)
  205. y = y1 + ua * (y2 - y1)
  206. m = QPointF((x3 + x4)/2, (y3 + y4)/2)
  207. d = distance(m - QPointF(x2, y2))
  208. yield d, i, (x, y)
  209. # These two, along with a call to adjustSize are required for the
  210. # scroll area.
  211. def sizeHint(self):
  212. return self.minimumSizeHint()
  213. def minimumSizeHint(self):
  214. if self.pixmap:
  215. return self.scale * self.pixmap.size()
  216. return super(Canvas, self).minimumSizeHint()
  217. def wheelEvent(self, ev):
  218. if ev.orientation() == Qt.Vertical:
  219. mods = ev.modifiers()
  220. if Qt.ControlModifier == int(mods):
  221. self.zoomRequest.emit(ev.delta())
  222. else:
  223. self.scrollRequest.emit(ev.delta(),
  224. Qt.Horizontal if (Qt.ShiftModifier == int(mods))\
  225. else Qt.Vertical)
  226. else:
  227. self.scrollRequest.emit(ev.delta(), Qt.Horizontal)
  228. ev.accept()
  229. def keyPressEvent(self, ev):
  230. if ev.key() == Qt.Key_Escape and self.current:
  231. self.current = None
  232. self.repaint()
  233. def setLastLabel(self, text):
  234. assert text
  235. print "shape <- '%s'" % text
  236. self.shapes[-1].label = text
  237. return self.shapes[-1]
  238. def undoLastLine(self):
  239. assert self.shapes
  240. self.current = self.shapes.pop()
  241. self.current.fill = False
  242. pos = self.current.popPoint()
  243. self.line.points = [self.current[-1], pos]
  244. self.setEditing()
  245. def deleteLastShape(self):
  246. assert self.shapes
  247. self.shapes.pop()
  248. def distance(p):
  249. return sqrt(p.x() * p.x() + p.y() * p.y())