canvas.py 18 KB

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