canvas.py 18 KB

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