canvas.py 16 KB

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