canvas.py 17 KB

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