canvas.py 16 KB

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