canvas.py 16 KB

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