canvas.py 12 KB

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