canvas.py 13 KB

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