canvas.py 11 KB

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