canvas.py 13 KB

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