canvas.py 18 KB

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