canvas.py 11 KB

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