canvas.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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.selectShape(pos)
  124. self.prevPoint = pos
  125. self.repaint()
  126. elif ev.button() == Qt.RightButton and not self.editing():
  127. self.selectShape(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, point):
  177. """Select the first shape created which contains this point."""
  178. self.deSelectShape()
  179. for shape in reversed(self.shapes):
  180. if self.isVisible(shape) and shape.containsPoint(point):
  181. shape.selected = True
  182. self.selectedShape = shape
  183. self.calculateOffsets(shape, point)
  184. self.setHiding()
  185. self.selectionChanged.emit(True)
  186. return
  187. def calculateOffsets(self, shape, point):
  188. rect = shape.boundingRect()
  189. x1 = rect.x() - point.x()
  190. y1 = rect.y() - point.y()
  191. x2 = (rect.x() + rect.width()) - point.x()
  192. y2 = (rect.y() + rect.height()) - point.y()
  193. self.offsets = QPointF(x1, y1), QPointF(x2, y2)
  194. def boundedMoveShape(self, shape, pos):
  195. if self.outOfPixmap(pos):
  196. return # No need to move
  197. o1 = pos + self.offsets[0]
  198. if self.outOfPixmap(o1):
  199. pos -= QPointF(min(0, o1.x()), min(0, o1.y()))
  200. o2 = pos + self.offsets[1]
  201. if self.outOfPixmap(o2):
  202. pos += QPointF(min(0, self.pixmap.width() - o2.x()),
  203. min(0, self.pixmap.height()- o2.y()))
  204. # The next line tracks the new position of the cursor
  205. # relative to the shape, but also results in making it
  206. # a bit "shaky" when nearing the border and allows it to
  207. # go outside of the shape's area for some reason. XXX
  208. #self.calculateOffsets(self.selectedShape, pos)
  209. shape.moveBy(pos - self.prevPoint)
  210. self.prevPoint = pos
  211. def deSelectShape(self):
  212. if self.selectedShape:
  213. self.selectedShape.selected = False
  214. self.selectedShape = None
  215. self.setHiding(False)
  216. self.repaint()
  217. self.selectionChanged.emit(False)
  218. def deleteSelected(self):
  219. if self.selectedShape:
  220. shape = self.selectedShape
  221. self.shapes.remove(self.selectedShape)
  222. self.selectedShape = None
  223. self.repaint()
  224. return shape
  225. def copySelectedShape(self):
  226. if self.selectedShape:
  227. shape = self.selectedShape.copy()
  228. self.shapes.append(shape)
  229. self.selectedShape = shape
  230. self.deSelectShape()
  231. self.repaint()
  232. return shape
  233. def paintEvent(self, event):
  234. if not self.pixmap:
  235. return super(Canvas, self).paintEvent(event)
  236. p = QPainter()
  237. p.begin(self)
  238. p.setRenderHint(QPainter.Antialiasing)
  239. p.setRenderHint(QPainter.SmoothPixmapTransform)
  240. p.scale(self.scale, self.scale)
  241. p.translate(self.offsetToCenter())
  242. p.drawPixmap(0, 0, self.pixmap)
  243. Shape.scale = self.scale
  244. for shape in self.shapes:
  245. if (shape.selected or not self._hideBackround) and self.isVisible(shape):
  246. shape.fill = shape.selected or self.highlightedShape == shape
  247. shape.paint(p)
  248. if self.current:
  249. self.current.paint(p)
  250. self.line.paint(p)
  251. if self.selectedShapeCopy:
  252. self.selectedShapeCopy.paint(p)
  253. p.end()
  254. def transformPos(self, point):
  255. """Convert from widget-logical coordinates to painter-logical coordinates."""
  256. return point / self.scale - self.offsetToCenter()
  257. def offsetToCenter(self):
  258. s = self.scale
  259. area = super(Canvas, self).size()
  260. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  261. aw, ah = area.width(), area.height()
  262. x = (aw-w)/(2*s) if aw > w else 0
  263. y = (ah-h)/(2*s) if ah > h else 0
  264. return QPointF(x, y)
  265. def outOfPixmap(self, p):
  266. w, h = self.pixmap.width(), self.pixmap.height()
  267. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  268. def finalise(self, ev):
  269. assert self.current
  270. self.shapes.append(self.current)
  271. self.current = None
  272. self.setEditing(False)
  273. self.setHiding(False)
  274. self.repaint()
  275. self.newShape.emit(self.mapToGlobal(ev.pos()))
  276. def closeEnough(self, p1, p2):
  277. #d = distance(p1 - p2)
  278. #m = (p1-p2).manhattanLength()
  279. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  280. return distance(p1 - p2) < self.epsilon
  281. def intersectionPoint(self, p1, p2):
  282. # Cycle through each image edge in clockwise fashion,
  283. # and find the one intersecting the current line segment.
  284. # http://paulbourke.net/geometry/lineline2d/
  285. size = self.pixmap.size()
  286. points = [(0,0),
  287. (size.width(), 0),
  288. (size.width(), size.height()),
  289. (0, size.height())]
  290. x1, y1 = p1.x(), p1.y()
  291. x2, y2 = p2.x(), p2.y()
  292. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  293. x3, y3 = points[i]
  294. x4, y4 = points[(i+1)%4]
  295. if (x, y) == (x1, y1):
  296. # Handle cases where previous point is on one of the edges.
  297. if x3 == x4:
  298. return QPointF(x3, min(max(0, y2), max(y3, y4)))
  299. else: # y3 == y4
  300. return QPointF(min(max(0, x2), max(x3, x4)), y3)
  301. return QPointF(x, y)
  302. def intersectingEdges(self, (x1, y1), (x2, y2), points):
  303. """For each edge formed by `points', yield the intersection
  304. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  305. Also return the distance of `(x2,y2)' to the middle of the
  306. edge along with its index, so that the one closest can be chosen."""
  307. for i in xrange(4):
  308. x3, y3 = points[i]
  309. x4, y4 = points[(i+1) % 4]
  310. denom = (y4-y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  311. nua = (x4-x3) * (y1-y3) - (y4-y3) * (x1-x3)
  312. nub = (x2-x1) * (y1-y3) - (y2-y1) * (x1-x3)
  313. if denom == 0:
  314. # This covers two cases:
  315. # nua == nub == 0: Coincident
  316. # otherwise: Parallel
  317. continue
  318. ua, ub = nua / denom, nub / denom
  319. if 0 <= ua <= 1 and 0 <= ub <= 1:
  320. x = x1 + ua * (x2 - x1)
  321. y = y1 + ua * (y2 - y1)
  322. m = QPointF((x3 + x4)/2, (y3 + y4)/2)
  323. d = distance(m - QPointF(x2, y2))
  324. yield d, i, (x, y)
  325. # These two, along with a call to adjustSize are required for the
  326. # scroll area.
  327. def sizeHint(self):
  328. return self.minimumSizeHint()
  329. def minimumSizeHint(self):
  330. if self.pixmap:
  331. return self.scale * self.pixmap.size()
  332. return super(Canvas, self).minimumSizeHint()
  333. def wheelEvent(self, ev):
  334. if ev.orientation() == Qt.Vertical:
  335. mods = ev.modifiers()
  336. if Qt.ControlModifier == int(mods):
  337. self.zoomRequest.emit(ev.delta())
  338. else:
  339. self.scrollRequest.emit(ev.delta(),
  340. Qt.Horizontal if (Qt.ShiftModifier == int(mods))\
  341. else Qt.Vertical)
  342. else:
  343. self.scrollRequest.emit(ev.delta(), Qt.Horizontal)
  344. ev.accept()
  345. def keyPressEvent(self, ev):
  346. if ev.key() == Qt.Key_Escape and self.current:
  347. self.current = None
  348. self.repaint()
  349. def setLastLabel(self, text):
  350. assert text
  351. print "shape <- '%s'" % text
  352. self.shapes[-1].label = text
  353. return self.shapes[-1]
  354. def undoLastLine(self):
  355. assert self.shapes
  356. self.current = self.shapes.pop()
  357. pos = self.current.popPoint()
  358. self.line.points = [self.current[-1], pos]
  359. self.setEditing()
  360. def deleteLastShape(self):
  361. assert self.shapes
  362. self.shapes.pop()
  363. def loadPixmap(self, pixmap):
  364. self.pixmap = pixmap
  365. self.shapes = []
  366. self.repaint()
  367. def loadShapes(self, shapes):
  368. self.shapes = list(shapes)
  369. self.current = None
  370. self.repaint()
  371. def copySelectedShape(self):
  372. if self.selectedShape:
  373. newShape=self.selectedShape.copy()
  374. self.shapes.append(newShape)
  375. self.deSelectShape()
  376. self.shapes[-1].selected=True
  377. self.selectedShape=self.shapes[-1]
  378. self.repaint()
  379. return self.selectedShape
  380. def setShapeVisible(self, shape, value):
  381. self.visible[shape] = value
  382. self.repaint()
  383. def overrideCursor(self, cursor):
  384. QApplication.setOverrideCursor(cursor)
  385. def restoreCursor(self):
  386. QApplication.restoreOverrideCursor()
  387. def pp(p):
  388. return '%.2f, %.2f' % (p.x(), p.y())
  389. def distance(p):
  390. return sqrt(p.x() * p.x() + p.y() * p.y())