canvas.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. CURSOR_DEFAULT = Qt.ArrowCursor
  11. CURSOR_DRAW = Qt.CrossCursor
  12. CURSOR_MOVE = Qt.ClosedHandCursor
  13. CURSOR_GRAB = Qt.OpenHandCursor
  14. class Canvas(QWidget):
  15. zoomRequest = pyqtSignal(int)
  16. scrollRequest = pyqtSignal(int, int)
  17. newShape = pyqtSignal(QPoint)
  18. selectionChanged = pyqtSignal(bool)
  19. shapeMoved = pyqtSignal()
  20. SELECT, EDIT = range(2)
  21. epsilon = 9.0
  22. def __init__(self, *args, **kwargs):
  23. super(Canvas, self).__init__(*args, **kwargs)
  24. # Initialise local state.
  25. self.mode = self.SELECT
  26. self.shapes = []
  27. self.current = None
  28. self.selectedShape=None # save the selected shape here
  29. self.selectedShapeCopy=None
  30. self.lineColor = QColor(0, 0, 255)
  31. self.line = Shape(line_color=self.lineColor)
  32. self.mouseButtonIsPressed=False #when it is true and shape is selected , move the shape with the mouse move event
  33. self.prevPoint = QPointF()
  34. self.offsets = QPointF(), QPointF()
  35. self.scale = 1.0
  36. self.pixmap = QPixmap()
  37. self.visible = {}
  38. self._hideBackround = False
  39. self.hideBackround = False
  40. self.highlightedShape = None
  41. # Menus:
  42. self.menus = (QMenu(), QMenu())
  43. # Set widget options.
  44. self.setMouseTracking(True)
  45. self.setFocusPolicy(Qt.WheelFocus)
  46. def focusOutEvent(self, ev):
  47. self.restoreCursor()
  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.selectShapePoint(pos)
  126. self.prevPoint = pos
  127. self.repaint()
  128. elif ev.button() == Qt.RightButton and not self.editing():
  129. self.selectShapePoint(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. self.restoreCursor()
  137. if not menu.exec_(self.mapToGlobal(ev.pos()))\
  138. and self.selectedShapeCopy:
  139. # Cancel the move by deleting the shadow copy.
  140. self.selectedShapeCopy = None
  141. self.repaint()
  142. elif ev.button() == Qt.LeftButton and self.selectedShape:
  143. self.overrideCursor(CURSOR_GRAB)
  144. def endMove(self, copy=False):
  145. assert self.selectedShape and self.selectedShapeCopy
  146. shape = self.selectedShapeCopy
  147. #del shape.fill_color
  148. #del shape.line_color
  149. if copy:
  150. self.shapes.append(shape)
  151. self.selectedShape.selected = False
  152. self.selectedShape = shape
  153. self.repaint()
  154. else:
  155. shape.label = self.selectedShape.label
  156. self.deleteSelected()
  157. self.shapes.append(shape)
  158. self.selectedShapeCopy = None
  159. def hideBackroundShapes(self, value):
  160. self.hideBackround = value
  161. if self.selectedShape:
  162. # Only hide other shapes if there is a current selection.
  163. # Otherwise the user will not be able to select a shape.
  164. self.setHiding(True)
  165. self.repaint()
  166. def setHiding(self, enable=True):
  167. self._hideBackround = self.hideBackround if enable else False
  168. def mouseDoubleClickEvent(self, ev):
  169. if self.current and self.editing():
  170. # Shapes need to have at least 3 vertices.
  171. if len(self.current) < 4:
  172. return
  173. # Replace the last point with the starting point.
  174. # We have to do this because the mousePressEvent handler
  175. # adds that point before this handler is called!
  176. self.current[-1] = self.current[0]
  177. self.finalise(ev)
  178. def selectShape(self, shape):
  179. self.deSelectShape()
  180. shape.selected = True
  181. self.selectedShape = shape
  182. self.setHiding()
  183. self.selectionChanged.emit(True)
  184. self.update()
  185. def selectShapePoint(self, point):
  186. """Select the first shape created which contains this point."""
  187. self.deSelectShape()
  188. for shape in reversed(self.shapes):
  189. if self.isVisible(shape) and shape.containsPoint(point):
  190. shape.selected = True
  191. self.selectedShape = shape
  192. self.calculateOffsets(shape, point)
  193. self.setHiding()
  194. self.selectionChanged.emit(True)
  195. return
  196. def calculateOffsets(self, shape, point):
  197. rect = shape.boundingRect()
  198. x1 = rect.x() - point.x()
  199. y1 = rect.y() - point.y()
  200. x2 = (rect.x() + rect.width()) - point.x()
  201. y2 = (rect.y() + rect.height()) - point.y()
  202. self.offsets = QPointF(x1, y1), QPointF(x2, y2)
  203. def boundedMoveShape(self, shape, pos):
  204. if self.outOfPixmap(pos):
  205. return # No need to move
  206. o1 = pos + self.offsets[0]
  207. if self.outOfPixmap(o1):
  208. pos -= QPointF(min(0, o1.x()), min(0, o1.y()))
  209. o2 = pos + self.offsets[1]
  210. if self.outOfPixmap(o2):
  211. pos += QPointF(min(0, self.pixmap.width() - o2.x()),
  212. min(0, self.pixmap.height()- o2.y()))
  213. # The next line tracks the new position of the cursor
  214. # relative to the shape, but also results in making it
  215. # a bit "shaky" when nearing the border and allows it to
  216. # go outside of the shape's area for some reason. XXX
  217. #self.calculateOffsets(self.selectedShape, pos)
  218. shape.moveBy(pos - self.prevPoint)
  219. self.prevPoint = pos
  220. def deSelectShape(self):
  221. if self.selectedShape:
  222. self.selectedShape.selected = False
  223. self.selectedShape = None
  224. self.setHiding(False)
  225. self.selectionChanged.emit(False)
  226. self.update()
  227. def deleteSelected(self):
  228. if self.selectedShape:
  229. shape = self.selectedShape
  230. self.shapes.remove(self.selectedShape)
  231. self.selectedShape = None
  232. self.update()
  233. return shape
  234. def copySelectedShape(self):
  235. if self.selectedShape:
  236. shape = self.selectedShape.copy()
  237. self.shapes.append(shape)
  238. self.selectedShape = shape
  239. self.deSelectShape()
  240. return shape
  241. def paintEvent(self, event):
  242. if not self.pixmap:
  243. return super(Canvas, self).paintEvent(event)
  244. p = QPainter()
  245. p.begin(self)
  246. p.setRenderHint(QPainter.Antialiasing)
  247. p.setRenderHint(QPainter.SmoothPixmapTransform)
  248. p.scale(self.scale, self.scale)
  249. p.translate(self.offsetToCenter())
  250. p.drawPixmap(0, 0, self.pixmap)
  251. Shape.scale = self.scale
  252. for shape in self.shapes:
  253. if (shape.selected or not self._hideBackround) and self.isVisible(shape):
  254. shape.fill = shape.selected or self.highlightedShape == shape
  255. shape.paint(p)
  256. if self.current:
  257. self.current.paint(p)
  258. self.line.paint(p)
  259. if self.selectedShapeCopy:
  260. self.selectedShapeCopy.paint(p)
  261. p.end()
  262. def transformPos(self, point):
  263. """Convert from widget-logical coordinates to painter-logical coordinates."""
  264. return point / self.scale - self.offsetToCenter()
  265. def offsetToCenter(self):
  266. s = self.scale
  267. area = super(Canvas, self).size()
  268. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  269. aw, ah = area.width(), area.height()
  270. x = (aw-w)/(2*s) if aw > w else 0
  271. y = (ah-h)/(2*s) if ah > h else 0
  272. return QPointF(x, y)
  273. def outOfPixmap(self, p):
  274. w, h = self.pixmap.width(), self.pixmap.height()
  275. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  276. def finalise(self, ev):
  277. assert self.current
  278. self.shapes.append(self.current)
  279. self.current = None
  280. self.setEditing(False)
  281. self.setHiding(False)
  282. self.repaint()
  283. self.newShape.emit(self.mapToGlobal(ev.pos()))
  284. def closeEnough(self, p1, p2):
  285. #d = distance(p1 - p2)
  286. #m = (p1-p2).manhattanLength()
  287. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  288. return distance(p1 - p2) < self.epsilon
  289. def intersectionPoint(self, p1, p2):
  290. # Cycle through each image edge in clockwise fashion,
  291. # and find the one intersecting the current line segment.
  292. # http://paulbourke.net/geometry/lineline2d/
  293. size = self.pixmap.size()
  294. points = [(0,0),
  295. (size.width(), 0),
  296. (size.width(), size.height()),
  297. (0, size.height())]
  298. x1, y1 = p1.x(), p1.y()
  299. x2, y2 = p2.x(), p2.y()
  300. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  301. x3, y3 = points[i]
  302. x4, y4 = points[(i+1)%4]
  303. if (x, y) == (x1, y1):
  304. # Handle cases where previous point is on one of the edges.
  305. if x3 == x4:
  306. return QPointF(x3, min(max(0, y2), max(y3, y4)))
  307. else: # y3 == y4
  308. return QPointF(min(max(0, x2), max(x3, x4)), y3)
  309. return QPointF(x, y)
  310. def intersectingEdges(self, (x1, y1), (x2, y2), points):
  311. """For each edge formed by `points', yield the intersection
  312. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  313. Also return the distance of `(x2,y2)' to the middle of the
  314. edge along with its index, so that the one closest can be chosen."""
  315. for i in xrange(4):
  316. x3, y3 = points[i]
  317. x4, y4 = points[(i+1) % 4]
  318. denom = (y4-y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  319. nua = (x4-x3) * (y1-y3) - (y4-y3) * (x1-x3)
  320. nub = (x2-x1) * (y1-y3) - (y2-y1) * (x1-x3)
  321. if denom == 0:
  322. # This covers two cases:
  323. # nua == nub == 0: Coincident
  324. # otherwise: Parallel
  325. continue
  326. ua, ub = nua / denom, nub / denom
  327. if 0 <= ua <= 1 and 0 <= ub <= 1:
  328. x = x1 + ua * (x2 - x1)
  329. y = y1 + ua * (y2 - y1)
  330. m = QPointF((x3 + x4)/2, (y3 + y4)/2)
  331. d = distance(m - QPointF(x2, y2))
  332. yield d, i, (x, y)
  333. # These two, along with a call to adjustSize are required for the
  334. # scroll area.
  335. def sizeHint(self):
  336. return self.minimumSizeHint()
  337. def minimumSizeHint(self):
  338. if self.pixmap:
  339. return self.scale * self.pixmap.size()
  340. return super(Canvas, self).minimumSizeHint()
  341. def wheelEvent(self, ev):
  342. if ev.orientation() == Qt.Vertical:
  343. mods = ev.modifiers()
  344. if Qt.ControlModifier == int(mods):
  345. self.zoomRequest.emit(ev.delta())
  346. else:
  347. self.scrollRequest.emit(ev.delta(),
  348. Qt.Horizontal if (Qt.ShiftModifier == int(mods))\
  349. else Qt.Vertical)
  350. else:
  351. self.scrollRequest.emit(ev.delta(), Qt.Horizontal)
  352. ev.accept()
  353. def keyPressEvent(self, ev):
  354. if ev.key() == Qt.Key_Escape and self.current:
  355. self.current = None
  356. self.repaint()
  357. def setLastLabel(self, text):
  358. assert text
  359. print "shape <- '%s'" % text
  360. self.shapes[-1].label = text
  361. return self.shapes[-1]
  362. def undoLastLine(self):
  363. assert self.shapes
  364. self.current = self.shapes.pop()
  365. pos = self.current.popPoint()
  366. self.line.points = [self.current[-1], pos]
  367. self.setEditing()
  368. def deleteLastShape(self):
  369. assert self.shapes
  370. self.shapes.pop()
  371. def loadPixmap(self, pixmap):
  372. self.pixmap = pixmap
  373. self.shapes = []
  374. self.repaint()
  375. def loadShapes(self, shapes):
  376. self.shapes = list(shapes)
  377. self.current = None
  378. self.repaint()
  379. def copySelectedShape(self):
  380. if self.selectedShape:
  381. newShape=self.selectedShape.copy()
  382. self.shapes.append(newShape)
  383. self.deSelectShape()
  384. self.shapes[-1].selected=True
  385. self.selectedShape=self.shapes[-1]
  386. self.repaint()
  387. return self.selectedShape
  388. def setShapeVisible(self, shape, value):
  389. self.visible[shape] = value
  390. self.repaint()
  391. def overrideCursor(self, cursor):
  392. QApplication.setOverrideCursor(cursor)
  393. def restoreCursor(self):
  394. QApplication.restoreOverrideCursor()
  395. def resetState(self):
  396. self.restoreCursor()
  397. self.pixmap = None
  398. self.update()
  399. def pp(p):
  400. return '%.2f, %.2f' % (p.x(), p.y())
  401. def distance(p):
  402. return sqrt(p.x() * p.x() + p.y() * p.y())