canvas.py 16 KB

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