canvas.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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 False # 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. dp = pos - self.prevPoint
  255. if dp:
  256. shape.moveBy(dp)
  257. self.prevPoint = pos
  258. return True
  259. return False
  260. def deSelectShape(self):
  261. if self.selectedShape:
  262. self.selectedShape.selected = False
  263. self.selectedShape = None
  264. self.setHiding(False)
  265. self.selectionChanged.emit(False)
  266. self.update()
  267. def deleteSelected(self):
  268. if self.selectedShape:
  269. shape = self.selectedShape
  270. self.shapes.remove(self.selectedShape)
  271. self.selectedShape = None
  272. self.update()
  273. return shape
  274. def copySelectedShape(self):
  275. if self.selectedShape:
  276. shape = self.selectedShape.copy()
  277. self.deSelectShape()
  278. self.shapes.append(shape)
  279. shape.selected = True
  280. self.selectedShape = shape
  281. self.boundedShiftShape(shape)
  282. return shape
  283. def boundedShiftShape(self, shape):
  284. # Try to move in one direction, and if it fails in another.
  285. # Give up if both fail.
  286. point = shape[0]
  287. offset = QPointF(2.0, 2.0)
  288. self.calculateOffsets(shape, point)
  289. self.prevPoint = point
  290. if not self.boundedMoveShape(shape, point - offset):
  291. self.boundedMoveShape(shape, point + offset)
  292. def paintEvent(self, event):
  293. if not self.pixmap:
  294. return super(Canvas, self).paintEvent(event)
  295. p = self._painter
  296. p.begin(self)
  297. p.setRenderHint(QPainter.Antialiasing)
  298. p.setRenderHint(QPainter.HighQualityAntialiasing)
  299. p.setRenderHint(QPainter.SmoothPixmapTransform)
  300. p.scale(self.scale, self.scale)
  301. p.translate(self.offsetToCenter())
  302. p.drawPixmap(0, 0, self.pixmap)
  303. Shape.scale = self.scale
  304. for shape in self.shapes:
  305. if (shape.selected or not self._hideBackround) and self.isVisible(shape):
  306. shape.fill = shape.selected or self.highlightedShape == shape
  307. shape.paint(p)
  308. if self.current:
  309. self.current.paint(p)
  310. self.line.paint(p)
  311. if self.selectedShapeCopy:
  312. self.selectedShapeCopy.paint(p)
  313. p.end()
  314. def transformPos(self, point):
  315. """Convert from widget-logical coordinates to painter-logical coordinates."""
  316. return point / self.scale - self.offsetToCenter()
  317. def offsetToCenter(self):
  318. s = self.scale
  319. area = super(Canvas, self).size()
  320. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  321. aw, ah = area.width(), area.height()
  322. x = (aw-w)/(2*s) if aw > w else 0
  323. y = (ah-h)/(2*s) if ah > h else 0
  324. return QPointF(x, y)
  325. def outOfPixmap(self, p):
  326. w, h = self.pixmap.width(), self.pixmap.height()
  327. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  328. def finalise(self, ev):
  329. assert self.current
  330. self.shapes.append(self.current)
  331. self.current = None
  332. self.setHiding(False)
  333. self.repaint()
  334. self.newShape.emit(self.mapToGlobal(ev.pos()))
  335. def closeEnough(self, p1, p2):
  336. #d = distance(p1 - p2)
  337. #m = (p1-p2).manhattanLength()
  338. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  339. return distance(p1 - p2) < self.epsilon
  340. def intersectionPoint(self, p1, p2):
  341. # Cycle through each image edge in clockwise fashion,
  342. # and find the one intersecting the current line segment.
  343. # http://paulbourke.net/geometry/lineline2d/
  344. size = self.pixmap.size()
  345. points = [(0,0),
  346. (size.width(), 0),
  347. (size.width(), size.height()),
  348. (0, size.height())]
  349. x1, y1 = p1.x(), p1.y()
  350. x2, y2 = p2.x(), p2.y()
  351. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  352. x3, y3 = points[i]
  353. x4, y4 = points[(i+1)%4]
  354. if (x, y) == (x1, y1):
  355. # Handle cases where previous point is on one of the edges.
  356. if x3 == x4:
  357. return QPointF(x3, min(max(0, y2), max(y3, y4)))
  358. else: # y3 == y4
  359. return QPointF(min(max(0, x2), max(x3, x4)), y3)
  360. return QPointF(x, y)
  361. def intersectingEdges(self, (x1, y1), (x2, y2), points):
  362. """For each edge formed by `points', yield the intersection
  363. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  364. Also return the distance of `(x2,y2)' to the middle of the
  365. edge along with its index, so that the one closest can be chosen."""
  366. for i in xrange(4):
  367. x3, y3 = points[i]
  368. x4, y4 = points[(i+1) % 4]
  369. denom = (y4-y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  370. nua = (x4-x3) * (y1-y3) - (y4-y3) * (x1-x3)
  371. nub = (x2-x1) * (y1-y3) - (y2-y1) * (x1-x3)
  372. if denom == 0:
  373. # This covers two cases:
  374. # nua == nub == 0: Coincident
  375. # otherwise: Parallel
  376. continue
  377. ua, ub = nua / denom, nub / denom
  378. if 0 <= ua <= 1 and 0 <= ub <= 1:
  379. x = x1 + ua * (x2 - x1)
  380. y = y1 + ua * (y2 - y1)
  381. m = QPointF((x3 + x4)/2, (y3 + y4)/2)
  382. d = distance(m - QPointF(x2, y2))
  383. yield d, i, (x, y)
  384. # These two, along with a call to adjustSize are required for the
  385. # scroll area.
  386. def sizeHint(self):
  387. return self.minimumSizeHint()
  388. def minimumSizeHint(self):
  389. if self.pixmap:
  390. return self.scale * self.pixmap.size()
  391. return super(Canvas, self).minimumSizeHint()
  392. def wheelEvent(self, ev):
  393. if ev.orientation() == Qt.Vertical:
  394. mods = ev.modifiers()
  395. if Qt.ControlModifier == int(mods):
  396. self.zoomRequest.emit(ev.delta())
  397. else:
  398. self.scrollRequest.emit(ev.delta(),
  399. Qt.Horizontal if (Qt.ShiftModifier == int(mods))\
  400. else Qt.Vertical)
  401. else:
  402. self.scrollRequest.emit(ev.delta(), Qt.Horizontal)
  403. ev.accept()
  404. def keyPressEvent(self, ev):
  405. if ev.key() == Qt.Key_Escape and self.current:
  406. self.current = None
  407. self.drawingPolygon.emit(False)
  408. self.update()
  409. def setLastLabel(self, text):
  410. assert text
  411. self.shapes[-1].label = text
  412. return self.shapes[-1]
  413. def undoLastLine(self):
  414. assert self.shapes
  415. self.current = self.shapes.pop()
  416. self.current.setOpen()
  417. self.line.points = [self.current[-1], self.current[0]]
  418. self.drawingPolygon.emit(True)
  419. def deleteLastShape(self):
  420. assert self.shapes
  421. self.shapes.pop()
  422. self.drawingPolygon.emit(False)
  423. def loadPixmap(self, pixmap):
  424. self.pixmap = pixmap
  425. self.shapes = []
  426. self.repaint()
  427. def loadShapes(self, shapes):
  428. self.shapes = list(shapes)
  429. self.current = None
  430. self.repaint()
  431. def setShapeVisible(self, shape, value):
  432. self.visible[shape] = value
  433. self.repaint()
  434. def overrideCursor(self, cursor):
  435. self.restoreCursor()
  436. self._cursor = cursor
  437. QApplication.setOverrideCursor(cursor)
  438. def restoreCursor(self):
  439. QApplication.restoreOverrideCursor()
  440. def resetState(self):
  441. self.restoreCursor()
  442. self.pixmap = None
  443. self.update()
  444. def pp(p):
  445. return '%.2f, %.2f' % (p.x(), p.y())