canvas.py 16 KB

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