canvas.py 16 KB

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