canvas.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. SELECT, EDIT = range(2)
  21. epsilon = 11.0
  22. def __init__(self, *args, **kwargs):
  23. super(Canvas, self).__init__(*args, **kwargs)
  24. # Initialise local state.
  25. self.mode = self.SELECT
  26. self.shapes = []
  27. self.current = None
  28. self.selectedShape=None # save the selected shape here
  29. self.selectedShapeCopy=None
  30. self.lineColor = QColor(0, 0, 255)
  31. self.line = Shape(line_color=self.lineColor)
  32. self.mouseButtonIsPressed=False #when it is true and shape is selected , move the shape with the mouse move event
  33. self.prevPoint = QPointF()
  34. self.offsets = QPointF(), QPointF()
  35. self.scale = 1.0
  36. self.pixmap = QPixmap()
  37. self.visible = {}
  38. self._hideBackround = False
  39. self.hideBackround = False
  40. self.highlightedShape = None
  41. self._painter = QPainter()
  42. self._cursor = CURSOR_DEFAULT
  43. # Menus:
  44. self.menus = (QMenu(), QMenu())
  45. # Set widget options.
  46. self.setMouseTracking(True)
  47. self.setFocusPolicy(Qt.WheelFocus)
  48. def enterEvent(self, ev):
  49. self.overrideCursor(self._cursor)
  50. def leaveEvent(self, ev):
  51. self.restoreCursor()
  52. def focusOutEvent(self, ev):
  53. self.restoreCursor()
  54. def isVisible(self, shape):
  55. return self.visible.get(shape, True)
  56. def editing(self):
  57. return self.mode == self.EDIT
  58. def setEditing(self, value=True):
  59. self.mode = self.EDIT if value else self.SELECT
  60. def mouseMoveEvent(self, ev):
  61. """Update line with last point and current coordinates."""
  62. pos = self.transformPos(ev.posF())
  63. self.restoreCursor()
  64. # Polygon drawing.
  65. if self.editing():
  66. self.overrideCursor(CURSOR_DRAW)
  67. if self.current:
  68. color = self.lineColor
  69. if self.outOfPixmap(pos):
  70. # Don't allow the user to draw outside the pixmap.
  71. # Project the point to the pixmap's edges.
  72. pos = self.intersectionPoint(self.current[-1], pos)
  73. elif len(self.current) > 1 and self.closeEnough(pos, self.current[0]):
  74. # Attract line to starting point and colorise to alert the user:
  75. pos = self.current[0]
  76. color = self.current.line_color
  77. self.overrideCursor(CURSOR_POINT)
  78. self.current.highlightStart = True
  79. self.line[1] = pos
  80. self.line.line_color = color
  81. self.repaint()
  82. self.current.highlightStart = False
  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. else:
  132. self.selectShapePoint(pos)
  133. self.prevPoint = pos
  134. self.repaint()
  135. elif ev.button() == Qt.RightButton and not self.editing():
  136. self.selectShapePoint(pos)
  137. self.prevPoint = pos
  138. self.repaint()
  139. def mouseReleaseEvent(self, ev):
  140. pos = self.transformPos(ev.posF())
  141. if ev.button() == Qt.RightButton:
  142. menu = self.menus[bool(self.selectedShapeCopy)]
  143. self.restoreCursor()
  144. if not menu.exec_(self.mapToGlobal(ev.pos()))\
  145. and self.selectedShapeCopy:
  146. # Cancel the move by deleting the shadow copy.
  147. self.selectedShapeCopy = None
  148. self.repaint()
  149. elif ev.button() == Qt.LeftButton and self.selectedShape:
  150. self.overrideCursor(CURSOR_GRAB)
  151. def endMove(self, copy=False):
  152. assert self.selectedShape and self.selectedShapeCopy
  153. shape = self.selectedShapeCopy
  154. #del shape.fill_color
  155. #del shape.line_color
  156. if copy:
  157. self.shapes.append(shape)
  158. self.selectedShape.selected = False
  159. self.selectedShape = shape
  160. self.repaint()
  161. else:
  162. shape.label = self.selectedShape.label
  163. self.deleteSelected()
  164. self.shapes.append(shape)
  165. self.selectedShapeCopy = None
  166. def hideBackroundShapes(self, value):
  167. self.hideBackround = value
  168. if self.selectedShape:
  169. # Only hide other shapes if there is a current selection.
  170. # Otherwise the user will not be able to select a shape.
  171. self.setHiding(True)
  172. self.repaint()
  173. def setHiding(self, enable=True):
  174. self._hideBackround = self.hideBackround if enable else False
  175. def mouseDoubleClickEvent(self, ev):
  176. if self.current and self.editing():
  177. # Shapes need to have at least 3 vertices.
  178. if len(self.current) < 4:
  179. return
  180. # Replace the last point with the starting point.
  181. # We have to do this because the mousePressEvent handler
  182. # adds that point before this handler is called!
  183. self.current[-1] = self.current[0]
  184. self.finalise(ev)
  185. def selectShape(self, shape):
  186. self.deSelectShape()
  187. shape.selected = True
  188. self.selectedShape = shape
  189. self.setHiding()
  190. self.selectionChanged.emit(True)
  191. self.update()
  192. def selectShapePoint(self, point):
  193. """Select the first shape created which contains this point."""
  194. self.deSelectShape()
  195. for shape in reversed(self.shapes):
  196. if self.isVisible(shape) and shape.containsPoint(point):
  197. shape.selected = True
  198. self.selectedShape = shape
  199. self.calculateOffsets(shape, point)
  200. self.setHiding()
  201. self.selectionChanged.emit(True)
  202. return
  203. def calculateOffsets(self, shape, point):
  204. rect = shape.boundingRect()
  205. x1 = rect.x() - point.x()
  206. y1 = rect.y() - point.y()
  207. x2 = (rect.x() + rect.width()) - point.x()
  208. y2 = (rect.y() + rect.height()) - point.y()
  209. self.offsets = QPointF(x1, y1), QPointF(x2, y2)
  210. def boundedMoveShape(self, shape, pos):
  211. if self.outOfPixmap(pos):
  212. return # No need to move
  213. o1 = pos + self.offsets[0]
  214. if self.outOfPixmap(o1):
  215. pos -= QPointF(min(0, o1.x()), min(0, o1.y()))
  216. o2 = pos + self.offsets[1]
  217. if self.outOfPixmap(o2):
  218. pos += QPointF(min(0, self.pixmap.width() - o2.x()),
  219. min(0, self.pixmap.height()- o2.y()))
  220. # The next line tracks the new position of the cursor
  221. # relative to the shape, but also results in making it
  222. # a bit "shaky" when nearing the border and allows it to
  223. # go outside of the shape's area for some reason. XXX
  224. #self.calculateOffsets(self.selectedShape, pos)
  225. shape.moveBy(pos - self.prevPoint)
  226. self.prevPoint = pos
  227. def deSelectShape(self):
  228. if self.selectedShape:
  229. self.selectedShape.selected = False
  230. self.selectedShape = None
  231. self.setHiding(False)
  232. self.selectionChanged.emit(False)
  233. self.update()
  234. def deleteSelected(self):
  235. if self.selectedShape:
  236. shape = self.selectedShape
  237. self.shapes.remove(self.selectedShape)
  238. self.selectedShape = None
  239. self.update()
  240. return shape
  241. def copySelectedShape(self):
  242. if self.selectedShape:
  243. shape = self.selectedShape.copy()
  244. self.shapes.append(shape)
  245. self.selectedShape = shape
  246. self.deSelectShape()
  247. return shape
  248. def paintEvent(self, event):
  249. if not self.pixmap:
  250. return super(Canvas, self).paintEvent(event)
  251. p = self._painter
  252. p.begin(self)
  253. p.setRenderHint(QPainter.Antialiasing)
  254. p.setRenderHint(QPainter.HighQualityAntialiasing)
  255. p.setRenderHint(QPainter.SmoothPixmapTransform)
  256. p.scale(self.scale, self.scale)
  257. p.translate(self.offsetToCenter())
  258. p.drawPixmap(0, 0, self.pixmap)
  259. Shape.scale = self.scale
  260. for shape in self.shapes:
  261. if (shape.selected or not self._hideBackround) and self.isVisible(shape):
  262. shape.fill = shape.selected or self.highlightedShape == shape
  263. shape.paint(p)
  264. if self.current:
  265. self.current.paint(p)
  266. self.line.paint(p)
  267. if self.selectedShapeCopy:
  268. self.selectedShapeCopy.paint(p)
  269. p.end()
  270. def transformPos(self, point):
  271. """Convert from widget-logical coordinates to painter-logical coordinates."""
  272. return point / self.scale - self.offsetToCenter()
  273. def offsetToCenter(self):
  274. s = self.scale
  275. area = super(Canvas, self).size()
  276. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  277. aw, ah = area.width(), area.height()
  278. x = (aw-w)/(2*s) if aw > w else 0
  279. y = (ah-h)/(2*s) if ah > h else 0
  280. return QPointF(x, y)
  281. def outOfPixmap(self, p):
  282. w, h = self.pixmap.width(), self.pixmap.height()
  283. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  284. def finalise(self, ev):
  285. assert self.current
  286. self.shapes.append(self.current)
  287. self.current = None
  288. self.setEditing(False)
  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.update()
  365. def setLastLabel(self, text):
  366. assert text
  367. self.shapes[-1].label = text
  368. return self.shapes[-1]
  369. def undoLastLine(self):
  370. assert self.shapes
  371. self.current = self.shapes.pop()
  372. pos = self.current.popPoint()
  373. self.line.points = [self.current[-1], pos]
  374. self.setEditing()
  375. def deleteLastShape(self):
  376. assert self.shapes
  377. self.shapes.pop()
  378. def loadPixmap(self, pixmap):
  379. self.pixmap = pixmap
  380. self.shapes = []
  381. self.repaint()
  382. def loadShapes(self, shapes):
  383. self.shapes = list(shapes)
  384. self.current = None
  385. self.repaint()
  386. def copySelectedShape(self):
  387. if self.selectedShape:
  388. newShape=self.selectedShape.copy()
  389. self.shapes.append(newShape)
  390. self.deSelectShape()
  391. self.shapes[-1].selected=True
  392. self.selectedShape=self.shapes[-1]
  393. self.repaint()
  394. return self.selectedShape
  395. def setShapeVisible(self, shape, value):
  396. self.visible[shape] = value
  397. self.repaint()
  398. def overrideCursor(self, cursor):
  399. self._cursor = cursor
  400. QApplication.setOverrideCursor(cursor)
  401. def restoreCursor(self):
  402. QApplication.restoreOverrideCursor()
  403. def resetState(self):
  404. self.restoreCursor()
  405. self.pixmap = None
  406. self.update()
  407. def pp(p):
  408. return '%.2f, %.2f' % (p.x(), p.y())
  409. def distance(p):
  410. return sqrt(p.x() * p.x() + p.y() * p.y())