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(ev)
  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 mouseDoubleClickEvent(self, ev):
  207. if self.current and self.drawing():
  208. # Shapes need to have at least 3 vertices.
  209. if len(self.current) < 4:
  210. return
  211. # Replace the last point with the starting point.
  212. # We have to do this because the mousePressEvent handler
  213. # adds that point before this handler is called!
  214. self.current.popPoint()
  215. self.current.addPoint(self.current[0])
  216. self.finalise(ev)
  217. def selectShape(self, shape):
  218. self.deSelectShape()
  219. shape.selected = True
  220. self.selectedShape = shape
  221. self.setHiding()
  222. self.selectionChanged.emit(True)
  223. self.update()
  224. def selectShapePoint(self, point):
  225. """Select the first shape created which contains this point."""
  226. self.deSelectShape()
  227. if self.selectedVertex(): # A vertex is marked for selection.
  228. index, shape = self.hVertex, self.hShape
  229. shape.highlightVertex(index, shape.MOVE_VERTEX)
  230. return
  231. for shape in reversed(self.shapes):
  232. if self.isVisible(shape) and shape.containsPoint(point):
  233. shape.selected = True
  234. self.selectedShape = shape
  235. self.calculateOffsets(shape, point)
  236. self.setHiding()
  237. self.selectionChanged.emit(True)
  238. return
  239. def calculateOffsets(self, shape, point):
  240. rect = shape.boundingRect()
  241. x1 = rect.x() - point.x()
  242. y1 = rect.y() - point.y()
  243. x2 = (rect.x() + rect.width()) - point.x()
  244. y2 = (rect.y() + rect.height()) - point.y()
  245. self.offsets = QPointF(x1, y1), QPointF(x2, y2)
  246. def boundedMoveVertex(self, pos):
  247. index, shape = self.hVertex, self.hShape
  248. point = shape[index]
  249. if self.outOfPixmap(pos):
  250. pos = self.intersectionPoint(point, pos)
  251. shape.moveVertexBy(index, pos - point)
  252. def boundedMoveShape(self, shape, pos):
  253. if self.outOfPixmap(pos):
  254. return False # No need to move
  255. o1 = pos + self.offsets[0]
  256. if self.outOfPixmap(o1):
  257. pos -= QPointF(min(0, o1.x()), min(0, o1.y()))
  258. o2 = pos + self.offsets[1]
  259. if self.outOfPixmap(o2):
  260. pos += QPointF(min(0, self.pixmap.width() - o2.x()),
  261. min(0, self.pixmap.height()- o2.y()))
  262. # The next line tracks the new position of the cursor
  263. # relative to the shape, but also results in making it
  264. # a bit "shaky" when nearing the border and allows it to
  265. # go outside of the shape's area for some reason. XXX
  266. #self.calculateOffsets(self.selectedShape, pos)
  267. dp = pos - self.prevPoint
  268. if dp:
  269. shape.moveBy(dp)
  270. self.prevPoint = pos
  271. return True
  272. return False
  273. def deSelectShape(self):
  274. if self.selectedShape:
  275. self.selectedShape.selected = False
  276. self.selectedShape = None
  277. self.setHiding(False)
  278. self.selectionChanged.emit(False)
  279. self.update()
  280. def deleteSelected(self):
  281. if self.selectedShape:
  282. shape = self.selectedShape
  283. self.shapes.remove(self.selectedShape)
  284. self.selectedShape = None
  285. self.update()
  286. return shape
  287. def copySelectedShape(self):
  288. if self.selectedShape:
  289. shape = self.selectedShape.copy()
  290. self.deSelectShape()
  291. self.shapes.append(shape)
  292. shape.selected = True
  293. self.selectedShape = shape
  294. self.boundedShiftShape(shape)
  295. return shape
  296. def boundedShiftShape(self, shape):
  297. # Try to move in one direction, and if it fails in another.
  298. # Give up if both fail.
  299. point = shape[0]
  300. offset = QPointF(2.0, 2.0)
  301. self.calculateOffsets(shape, point)
  302. self.prevPoint = point
  303. if not self.boundedMoveShape(shape, point - offset):
  304. self.boundedMoveShape(shape, point + offset)
  305. def paintEvent(self, event):
  306. if not self.pixmap:
  307. return super(Canvas, self).paintEvent(event)
  308. p = self._painter
  309. p.begin(self)
  310. p.setRenderHint(QPainter.Antialiasing)
  311. p.setRenderHint(QPainter.HighQualityAntialiasing)
  312. p.setRenderHint(QPainter.SmoothPixmapTransform)
  313. p.scale(self.scale, self.scale)
  314. p.translate(self.offsetToCenter())
  315. p.drawPixmap(0, 0, self.pixmap)
  316. Shape.scale = self.scale
  317. for shape in self.shapes:
  318. if (shape.selected or not self._hideBackround) and self.isVisible(shape):
  319. shape.fill = shape.selected or shape == self.hShape
  320. shape.paint(p)
  321. if self.current:
  322. self.current.paint(p)
  323. self.line.paint(p)
  324. if self.selectedShapeCopy:
  325. self.selectedShapeCopy.paint(p)
  326. p.end()
  327. def transformPos(self, point):
  328. """Convert from widget-logical coordinates to painter-logical coordinates."""
  329. return point / self.scale - self.offsetToCenter()
  330. def offsetToCenter(self):
  331. s = self.scale
  332. area = super(Canvas, self).size()
  333. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  334. aw, ah = area.width(), area.height()
  335. x = (aw-w)/(2*s) if aw > w else 0
  336. y = (ah-h)/(2*s) if ah > h else 0
  337. return QPointF(x, y)
  338. def outOfPixmap(self, p):
  339. w, h = self.pixmap.width(), self.pixmap.height()
  340. return not (0 <= p.x() <= w and 0 <= p.y() <= h)
  341. def finalise(self, ev):
  342. assert self.current
  343. self.shapes.append(self.current)
  344. self.current = None
  345. self.setHiding(False)
  346. self.repaint()
  347. self.newShape.emit(self.mapToGlobal(ev.pos()))
  348. def closeEnough(self, p1, p2):
  349. #d = distance(p1 - p2)
  350. #m = (p1-p2).manhattanLength()
  351. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  352. return distance(p1 - p2) < self.epsilon
  353. def intersectionPoint(self, p1, p2):
  354. # Cycle through each image edge in clockwise fashion,
  355. # and find the one intersecting the current line segment.
  356. # http://paulbourke.net/geometry/lineline2d/
  357. size = self.pixmap.size()
  358. points = [(0,0),
  359. (size.width(), 0),
  360. (size.width(), size.height()),
  361. (0, size.height())]
  362. x1, y1 = p1.x(), p1.y()
  363. x2, y2 = p2.x(), p2.y()
  364. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  365. x3, y3 = points[i]
  366. x4, y4 = points[(i+1)%4]
  367. if (x, y) == (x1, y1):
  368. # Handle cases where previous point is on one of the edges.
  369. if x3 == x4:
  370. return QPointF(x3, min(max(0, y2), max(y3, y4)))
  371. else: # y3 == y4
  372. return QPointF(min(max(0, x2), max(x3, x4)), y3)
  373. return QPointF(x, y)
  374. def intersectingEdges(self, (x1, y1), (x2, y2), points):
  375. """For each edge formed by `points', yield the intersection
  376. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  377. Also return the distance of `(x2,y2)' to the middle of the
  378. edge along with its index, so that the one closest can be chosen."""
  379. for i in xrange(4):
  380. x3, y3 = points[i]
  381. x4, y4 = points[(i+1) % 4]
  382. denom = (y4-y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  383. nua = (x4-x3) * (y1-y3) - (y4-y3) * (x1-x3)
  384. nub = (x2-x1) * (y1-y3) - (y2-y1) * (x1-x3)
  385. if denom == 0:
  386. # This covers two cases:
  387. # nua == nub == 0: Coincident
  388. # otherwise: Parallel
  389. continue
  390. ua, ub = nua / denom, nub / denom
  391. if 0 <= ua <= 1 and 0 <= ub <= 1:
  392. x = x1 + ua * (x2 - x1)
  393. y = y1 + ua * (y2 - y1)
  394. m = QPointF((x3 + x4)/2, (y3 + y4)/2)
  395. d = distance(m - QPointF(x2, y2))
  396. yield d, i, (x, y)
  397. # These two, along with a call to adjustSize are required for the
  398. # scroll area.
  399. def sizeHint(self):
  400. return self.minimumSizeHint()
  401. def minimumSizeHint(self):
  402. if self.pixmap:
  403. return self.scale * self.pixmap.size()
  404. return super(Canvas, self).minimumSizeHint()
  405. def wheelEvent(self, ev):
  406. if ev.orientation() == Qt.Vertical:
  407. mods = ev.modifiers()
  408. if Qt.ControlModifier == int(mods):
  409. self.zoomRequest.emit(ev.delta())
  410. else:
  411. self.scrollRequest.emit(ev.delta(),
  412. Qt.Horizontal if (Qt.ShiftModifier == int(mods))\
  413. else Qt.Vertical)
  414. else:
  415. self.scrollRequest.emit(ev.delta(), Qt.Horizontal)
  416. ev.accept()
  417. def keyPressEvent(self, ev):
  418. if ev.key() == Qt.Key_Escape and self.current:
  419. self.current = None
  420. self.drawingPolygon.emit(False)
  421. self.update()
  422. def setLastLabel(self, text):
  423. assert text
  424. self.shapes[-1].label = text
  425. return self.shapes[-1]
  426. def undoLastLine(self):
  427. assert self.shapes
  428. self.current = self.shapes.pop()
  429. self.current.setOpen()
  430. self.line.points = [self.current[-1], self.current[0]]
  431. self.drawingPolygon.emit(True)
  432. def deleteLastShape(self):
  433. assert self.shapes
  434. self.shapes.pop()
  435. self.drawingPolygon.emit(False)
  436. def loadPixmap(self, pixmap):
  437. self.pixmap = pixmap
  438. self.shapes = []
  439. self.repaint()
  440. def loadShapes(self, shapes):
  441. self.shapes = list(shapes)
  442. self.current = None
  443. self.repaint()
  444. def setShapeVisible(self, shape, value):
  445. self.visible[shape] = value
  446. self.repaint()
  447. def overrideCursor(self, cursor):
  448. self.restoreCursor()
  449. self._cursor = cursor
  450. QApplication.setOverrideCursor(cursor)
  451. def restoreCursor(self):
  452. QApplication.restoreOverrideCursor()
  453. def resetState(self):
  454. self.restoreCursor()
  455. self.pixmap = None
  456. self.update()
  457. def pp(p):
  458. return '%.2f, %.2f' % (p.x(), p.y())