canvas.py 17 KB

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