canvas.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. from qtpy import QtCore
  2. from qtpy import QtGui
  3. from qtpy import QtWidgets
  4. from labelme import QT5
  5. from labelme.shape import Shape
  6. import labelme.utils
  7. # TODO(unknown):
  8. # - [maybe] Find optimal epsilon value.
  9. CURSOR_DEFAULT = QtCore.Qt.ArrowCursor
  10. CURSOR_POINT = QtCore.Qt.PointingHandCursor
  11. CURSOR_DRAW = QtCore.Qt.CrossCursor
  12. CURSOR_MOVE = QtCore.Qt.ClosedHandCursor
  13. CURSOR_GRAB = QtCore.Qt.OpenHandCursor
  14. class Canvas(QtWidgets.QWidget):
  15. zoomRequest = QtCore.Signal(int, QtCore.QPoint)
  16. scrollRequest = QtCore.Signal(int, int)
  17. newShape = QtCore.Signal()
  18. selectionChanged = QtCore.Signal(bool)
  19. shapeMoved = QtCore.Signal()
  20. drawingPolygon = QtCore.Signal(bool)
  21. edgeSelected = QtCore.Signal(bool)
  22. CREATE, EDIT = 0, 1
  23. # polygon, rectangle, line, or point
  24. _createMode = 'polygon'
  25. _fill_drawing = False
  26. def __init__(self, *args, **kwargs):
  27. self.epsilon = kwargs.pop('epsilon', 10.0)
  28. super(Canvas, self).__init__(*args, **kwargs)
  29. # Initialise local state.
  30. self.mode = self.EDIT
  31. self.shapes = []
  32. self.shapesBackups = []
  33. self.current = None
  34. self.selectedShape = None # save the selected shape here
  35. self.selectedShapeCopy = None
  36. self.lineColor = QtGui.QColor(0, 0, 255)
  37. # self.line represents:
  38. # - createMode == 'polygon': edge from last point to current
  39. # - createMode == 'rectangle': diagonal line of the rectangle
  40. # - createMode == 'line': the line
  41. # - createMode == 'point': the point
  42. self.line = Shape(line_color=self.lineColor)
  43. self.prevPoint = QtCore.QPoint()
  44. self.prevMovePoint = QtCore.QPoint()
  45. self.offsets = QtCore.QPoint(), QtCore.QPoint()
  46. self.scale = 1.0
  47. self.pixmap = QtGui.QPixmap()
  48. self.visible = {}
  49. self._hideBackround = False
  50. self.hideBackround = False
  51. self.hShape = None
  52. self.hVertex = None
  53. self.hEdge = None
  54. self.movingShape = False
  55. self._painter = QtGui.QPainter()
  56. self._cursor = CURSOR_DEFAULT
  57. # Menus:
  58. self.menus = (QtWidgets.QMenu(), QtWidgets.QMenu())
  59. # Set widget options.
  60. self.setMouseTracking(True)
  61. self.setFocusPolicy(QtCore.Qt.WheelFocus)
  62. def fillDrawing(self):
  63. return self._fill_drawing
  64. def setFillDrawing(self, value):
  65. self._fill_drawing = value
  66. @property
  67. def createMode(self):
  68. return self._createMode
  69. @createMode.setter
  70. def createMode(self, value):
  71. if value not in ['polygon', 'rectangle', 'circle',
  72. 'line', 'point', 'linestrip']:
  73. raise ValueError('Unsupported createMode: %s' % value)
  74. self._createMode = value
  75. def storeShapes(self):
  76. shapesBackup = []
  77. for shape in self.shapes:
  78. shapesBackup.append(shape.copy())
  79. if len(self.shapesBackups) >= 10:
  80. self.shapesBackups = self.shapesBackups[-9:]
  81. self.shapesBackups.append(shapesBackup)
  82. @property
  83. def isShapeRestorable(self):
  84. if len(self.shapesBackups) < 2:
  85. return False
  86. return True
  87. def restoreShape(self):
  88. if not self.isShapeRestorable:
  89. return
  90. self.shapesBackups.pop() # latest
  91. shapesBackup = self.shapesBackups.pop()
  92. self.shapes = shapesBackup
  93. self.storeShapes()
  94. self.repaint()
  95. def enterEvent(self, ev):
  96. self.overrideCursor(self._cursor)
  97. def leaveEvent(self, ev):
  98. self.restoreCursor()
  99. def focusOutEvent(self, ev):
  100. self.restoreCursor()
  101. def isVisible(self, shape):
  102. return self.visible.get(shape, True)
  103. def drawing(self):
  104. return self.mode == self.CREATE
  105. def editing(self):
  106. return self.mode == self.EDIT
  107. def setEditing(self, value=True):
  108. self.mode = self.EDIT if value else self.CREATE
  109. if not value: # Create
  110. self.unHighlight()
  111. self.deSelectShape()
  112. def unHighlight(self):
  113. if self.hShape:
  114. self.hShape.highlightClear()
  115. self.hVertex = self.hShape = None
  116. def selectedVertex(self):
  117. return self.hVertex is not None
  118. def mouseMoveEvent(self, ev):
  119. """Update line with last point and current coordinates."""
  120. try:
  121. if QT5:
  122. pos = self.transformPos(ev.pos())
  123. else:
  124. pos = self.transformPos(ev.posF())
  125. except AttributeError:
  126. return
  127. self.prevMovePoint = pos
  128. self.restoreCursor()
  129. # Polygon drawing.
  130. if self.drawing():
  131. self.line.shape_type = self.createMode
  132. self.overrideCursor(CURSOR_DRAW)
  133. if not self.current:
  134. return
  135. color = self.lineColor
  136. if self.outOfPixmap(pos):
  137. # Don't allow the user to draw outside the pixmap.
  138. # Project the point to the pixmap's edges.
  139. pos = self.intersectionPoint(self.current[-1], pos)
  140. elif len(self.current) > 1 and self.createMode == 'polygon' and\
  141. self.closeEnough(pos, self.current[0]):
  142. # Attract line to starting point and
  143. # colorise to alert the user.
  144. pos = self.current[0]
  145. color = self.current.line_color
  146. self.overrideCursor(CURSOR_POINT)
  147. self.current.highlightVertex(0, Shape.NEAR_VERTEX)
  148. if self.createMode in ['polygon', 'linestrip']:
  149. self.line[0] = self.current[-1]
  150. self.line[1] = pos
  151. elif self.createMode == 'rectangle':
  152. self.line.points = [self.current[0], pos]
  153. self.line.close()
  154. elif self.createMode == 'circle':
  155. self.line.points = [self.current[0], pos]
  156. self.line.shape_type = "circle"
  157. elif self.createMode == 'line':
  158. self.line.points = [self.current[0], pos]
  159. self.line.close()
  160. elif self.createMode == 'point':
  161. self.line.points = [self.current[0]]
  162. self.line.close()
  163. self.line.line_color = color
  164. self.repaint()
  165. self.current.highlightClear()
  166. return
  167. # Polygon copy moving.
  168. if QtCore.Qt.RightButton & ev.buttons():
  169. if self.selectedShapeCopy and self.prevPoint:
  170. self.overrideCursor(CURSOR_MOVE)
  171. self.boundedMoveShape(self.selectedShapeCopy, pos)
  172. self.repaint()
  173. elif self.selectedShape:
  174. self.selectedShapeCopy = self.selectedShape.copy()
  175. self.repaint()
  176. return
  177. # Polygon/Vertex moving.
  178. self.movingShape = False
  179. if QtCore.Qt.LeftButton & ev.buttons():
  180. if self.selectedVertex():
  181. self.boundedMoveVertex(pos)
  182. self.repaint()
  183. self.movingShape = True
  184. elif self.selectedShape and self.prevPoint:
  185. self.overrideCursor(CURSOR_MOVE)
  186. self.boundedMoveShape(self.selectedShape, pos)
  187. self.repaint()
  188. self.movingShape = True
  189. return
  190. # Just hovering over the canvas, 2 posibilities:
  191. # - Highlight shapes
  192. # - Highlight vertex
  193. # Update shape/vertex fill and tooltip value accordingly.
  194. self.setToolTip("Image")
  195. for shape in reversed([s for s in self.shapes if self.isVisible(s)]):
  196. # Look for a nearby vertex to highlight. If that fails,
  197. # check if we happen to be inside a shape.
  198. index = shape.nearestVertex(pos, self.epsilon)
  199. index_edge = shape.nearestEdge(pos, self.epsilon)
  200. if index is not None:
  201. if self.selectedVertex():
  202. self.hShape.highlightClear()
  203. self.hVertex = index
  204. self.hShape = shape
  205. self.hEdge = index_edge
  206. shape.highlightVertex(index, shape.MOVE_VERTEX)
  207. self.overrideCursor(CURSOR_POINT)
  208. self.setToolTip("Click & drag to move point")
  209. self.setStatusTip(self.toolTip())
  210. self.update()
  211. break
  212. elif shape.containsPoint(pos):
  213. if self.selectedVertex():
  214. self.hShape.highlightClear()
  215. self.hVertex = None
  216. self.hShape = shape
  217. self.hEdge = index_edge
  218. self.setToolTip(
  219. "Click & drag to move shape '%s'" % shape.label)
  220. self.setStatusTip(self.toolTip())
  221. self.overrideCursor(CURSOR_GRAB)
  222. self.update()
  223. break
  224. else: # Nothing found, clear highlights, reset state.
  225. if self.hShape:
  226. self.hShape.highlightClear()
  227. self.update()
  228. self.hVertex, self.hShape, self.hEdge = None, None, None
  229. self.edgeSelected.emit(self.hEdge is not None)
  230. def addPointToEdge(self):
  231. if (self.hShape is None and
  232. self.hEdge is None and
  233. self.prevMovePoint is None):
  234. return
  235. shape = self.hShape
  236. index = self.hEdge
  237. point = self.prevMovePoint
  238. shape.insertPoint(index, point)
  239. shape.highlightVertex(index, shape.MOVE_VERTEX)
  240. self.hShape = shape
  241. self.hVertex = index
  242. self.hEdge = None
  243. def mousePressEvent(self, ev):
  244. if QT5:
  245. pos = self.transformPos(ev.pos())
  246. else:
  247. pos = self.transformPos(ev.posF())
  248. if ev.button() == QtCore.Qt.LeftButton:
  249. if self.drawing():
  250. if self.current:
  251. # Add point to existing shape.
  252. if self.createMode == 'polygon':
  253. self.current.addPoint(self.line[1])
  254. self.line[0] = self.current[-1]
  255. if self.current.isClosed():
  256. self.finalise()
  257. elif self.createMode in ['rectangle', 'circle', 'line']:
  258. assert len(self.current.points) == 1
  259. self.current.points = self.line.points
  260. self.finalise()
  261. elif self.createMode == 'linestrip':
  262. self.current.addPoint(self.line[1])
  263. self.line[0] = self.current[-1]
  264. if int(ev.modifiers()) == QtCore.Qt.ControlModifier:
  265. self.finalise()
  266. elif not self.outOfPixmap(pos):
  267. # Create new shape.
  268. self.current = Shape(shape_type=self.createMode)
  269. self.current.addPoint(pos)
  270. if self.createMode == 'point':
  271. self.finalise()
  272. else:
  273. if self.createMode == 'circle':
  274. self.current.shape_type = 'circle'
  275. self.line.points = [pos, pos]
  276. self.setHiding()
  277. self.drawingPolygon.emit(True)
  278. self.update()
  279. else:
  280. self.selectShapePoint(pos)
  281. self.prevPoint = pos
  282. self.repaint()
  283. elif ev.button() == QtCore.Qt.RightButton and self.editing():
  284. self.selectShapePoint(pos)
  285. self.prevPoint = pos
  286. self.repaint()
  287. def mouseReleaseEvent(self, ev):
  288. if ev.button() == QtCore.Qt.RightButton:
  289. menu = self.menus[bool(self.selectedShapeCopy)]
  290. self.restoreCursor()
  291. if not menu.exec_(self.mapToGlobal(ev.pos()))\
  292. and self.selectedShapeCopy:
  293. # Cancel the move by deleting the shadow copy.
  294. self.selectedShapeCopy = None
  295. self.repaint()
  296. elif ev.button() == QtCore.Qt.LeftButton and self.selectedShape:
  297. self.overrideCursor(CURSOR_GRAB)
  298. if self.movingShape:
  299. self.storeShapes()
  300. self.shapeMoved.emit()
  301. def endMove(self, copy=False):
  302. assert self.selectedShape and self.selectedShapeCopy
  303. shape = self.selectedShapeCopy
  304. # del shape.fill_color
  305. # del shape.line_color
  306. if copy:
  307. self.shapes.append(shape)
  308. self.selectedShape.selected = False
  309. self.selectedShape = shape
  310. self.repaint()
  311. else:
  312. shape.label = self.selectedShape.label
  313. self.deleteSelected()
  314. self.shapes.append(shape)
  315. self.storeShapes()
  316. self.selectedShapeCopy = None
  317. def hideBackroundShapes(self, value):
  318. self.hideBackround = value
  319. if self.selectedShape:
  320. # Only hide other shapes if there is a current selection.
  321. # Otherwise the user will not be able to select a shape.
  322. self.setHiding(True)
  323. self.repaint()
  324. def setHiding(self, enable=True):
  325. self._hideBackround = self.hideBackround if enable else False
  326. def canCloseShape(self):
  327. return self.drawing() and self.current and len(self.current) > 2
  328. def mouseDoubleClickEvent(self, ev):
  329. # We need at least 4 points here, since the mousePress handler
  330. # adds an extra one before this handler is called.
  331. if self.canCloseShape() and len(self.current) > 3:
  332. self.current.popPoint()
  333. self.finalise()
  334. def selectShape(self, shape):
  335. self.deSelectShape()
  336. shape.selected = True
  337. self.selectedShape = shape
  338. self.setHiding()
  339. self.selectionChanged.emit(True)
  340. self.update()
  341. def selectShapePoint(self, point):
  342. """Select the first shape created which contains this point."""
  343. self.deSelectShape()
  344. if self.selectedVertex(): # A vertex is marked for selection.
  345. index, shape = self.hVertex, self.hShape
  346. shape.highlightVertex(index, shape.MOVE_VERTEX)
  347. return
  348. for shape in reversed(self.shapes):
  349. if self.isVisible(shape) and shape.containsPoint(point):
  350. shape.selected = True
  351. self.selectedShape = shape
  352. self.calculateOffsets(shape, point)
  353. self.setHiding()
  354. self.selectionChanged.emit(True)
  355. return
  356. def calculateOffsets(self, shape, point):
  357. rect = shape.boundingRect()
  358. x1 = rect.x() - point.x()
  359. y1 = rect.y() - point.y()
  360. x2 = (rect.x() + rect.width() - 1) - point.x()
  361. y2 = (rect.y() + rect.height() - 1) - point.y()
  362. self.offsets = QtCore.QPoint(x1, y1), QtCore.QPoint(x2, y2)
  363. def boundedMoveVertex(self, pos):
  364. index, shape = self.hVertex, self.hShape
  365. point = shape[index]
  366. if self.outOfPixmap(pos):
  367. pos = self.intersectionPoint(point, pos)
  368. shape.moveVertexBy(index, pos - point)
  369. def boundedMoveShape(self, shape, pos):
  370. if self.outOfPixmap(pos):
  371. return False # No need to move
  372. o1 = pos + self.offsets[0]
  373. if self.outOfPixmap(o1):
  374. pos -= QtCore.QPoint(min(0, o1.x()), min(0, o1.y()))
  375. o2 = pos + self.offsets[1]
  376. if self.outOfPixmap(o2):
  377. pos += QtCore.QPoint(min(0, self.pixmap.width() - o2.x()),
  378. min(0, self.pixmap.height() - o2.y()))
  379. # XXX: The next line tracks the new position of the cursor
  380. # relative to the shape, but also results in making it
  381. # a bit "shaky" when nearing the border and allows it to
  382. # go outside of the shape's area for some reason.
  383. # self.calculateOffsets(self.selectedShape, pos)
  384. dp = pos - self.prevPoint
  385. if dp:
  386. shape.moveBy(dp)
  387. self.prevPoint = pos
  388. return True
  389. return False
  390. def deSelectShape(self):
  391. if self.selectedShape:
  392. self.selectedShape.selected = False
  393. self.selectedShape = None
  394. self.setHiding(False)
  395. self.selectionChanged.emit(False)
  396. self.update()
  397. def deleteSelected(self):
  398. if self.selectedShape:
  399. shape = self.selectedShape
  400. self.shapes.remove(self.selectedShape)
  401. self.storeShapes()
  402. self.selectedShape = None
  403. self.update()
  404. return shape
  405. def copySelectedShape(self):
  406. if self.selectedShape:
  407. shape = self.selectedShape.copy()
  408. self.deSelectShape()
  409. self.shapes.append(shape)
  410. self.storeShapes()
  411. shape.selected = True
  412. self.selectedShape = shape
  413. self.boundedShiftShape(shape)
  414. return shape
  415. def boundedShiftShape(self, shape):
  416. # Try to move in one direction, and if it fails in another.
  417. # Give up if both fail.
  418. point = shape[0]
  419. offset = QtCore.QPoint(2.0, 2.0)
  420. self.calculateOffsets(shape, point)
  421. self.prevPoint = point
  422. if not self.boundedMoveShape(shape, point - offset):
  423. self.boundedMoveShape(shape, point + offset)
  424. def paintEvent(self, event):
  425. if not self.pixmap:
  426. return super(Canvas, self).paintEvent(event)
  427. p = self._painter
  428. p.begin(self)
  429. p.setRenderHint(QtGui.QPainter.Antialiasing)
  430. p.setRenderHint(QtGui.QPainter.HighQualityAntialiasing)
  431. p.setRenderHint(QtGui.QPainter.SmoothPixmapTransform)
  432. p.scale(self.scale, self.scale)
  433. p.translate(self.offsetToCenter())
  434. p.drawPixmap(0, 0, self.pixmap)
  435. Shape.scale = self.scale
  436. for shape in self.shapes:
  437. if (shape.selected or not self._hideBackround) and \
  438. self.isVisible(shape):
  439. shape.fill = shape.selected or shape == self.hShape
  440. shape.paint(p)
  441. if self.current:
  442. self.current.paint(p)
  443. self.line.paint(p)
  444. if self.selectedShapeCopy:
  445. self.selectedShapeCopy.paint(p)
  446. if (self.fillDrawing() and self.createMode == 'polygon' and
  447. self.current is not None and len(self.current.points) >= 2):
  448. drawing_shape = self.current.copy()
  449. drawing_shape.addPoint(self.line[1])
  450. drawing_shape.fill = True
  451. drawing_shape.fill_color.setAlpha(64)
  452. drawing_shape.paint(p)
  453. p.end()
  454. def transformPos(self, point):
  455. """Convert from widget-logical coordinates to painter-logical ones."""
  456. return point / self.scale - self.offsetToCenter()
  457. def offsetToCenter(self):
  458. s = self.scale
  459. area = super(Canvas, self).size()
  460. w, h = self.pixmap.width() * s, self.pixmap.height() * s
  461. aw, ah = area.width(), area.height()
  462. x = (aw - w) / (2 * s) if aw > w else 0
  463. y = (ah - h) / (2 * s) if ah > h else 0
  464. return QtCore.QPoint(x, y)
  465. def outOfPixmap(self, p):
  466. w, h = self.pixmap.width(), self.pixmap.height()
  467. return not (0 <= p.x() < w and 0 <= p.y() < h)
  468. def finalise(self):
  469. assert self.current
  470. self.current.close()
  471. self.shapes.append(self.current)
  472. self.storeShapes()
  473. self.current = None
  474. self.setHiding(False)
  475. self.newShape.emit()
  476. self.update()
  477. def closeEnough(self, p1, p2):
  478. # d = distance(p1 - p2)
  479. # m = (p1-p2).manhattanLength()
  480. # print "d %.2f, m %d, %.2f" % (d, m, d - m)
  481. # divide by scale to allow more precision when zoomed in
  482. return labelme.utils.distance(p1 - p2) < (self.epsilon / self.scale)
  483. def intersectionPoint(self, p1, p2):
  484. # Cycle through each image edge in clockwise fashion,
  485. # and find the one intersecting the current line segment.
  486. # http://paulbourke.net/geometry/lineline2d/
  487. size = self.pixmap.size()
  488. points = [(0, 0),
  489. (size.width() - 1, 0),
  490. (size.width() - 1, size.height() - 1),
  491. (0, size.height() - 1)]
  492. x1, y1 = p1.x(), p1.y()
  493. x2, y2 = p2.x(), p2.y()
  494. d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
  495. x3, y3 = points[i]
  496. x4, y4 = points[(i + 1) % 4]
  497. if (x, y) == (x1, y1):
  498. # Handle cases where previous point is on one of the edges.
  499. if x3 == x4:
  500. return QtCore.QPoint(x3, min(max(0, y2), max(y3, y4)))
  501. else: # y3 == y4
  502. return QtCore.QPoint(min(max(0, x2), max(x3, x4)), y3)
  503. return QtCore.QPoint(x, y)
  504. def intersectingEdges(self, point1, point2, points):
  505. """Find intersecting edges.
  506. For each edge formed by `points', yield the intersection
  507. with the line segment `(x1,y1) - (x2,y2)`, if it exists.
  508. Also return the distance of `(x2,y2)' to the middle of the
  509. edge along with its index, so that the one closest can be chosen.
  510. """
  511. (x1, y1) = point1
  512. (x2, y2) = point2
  513. for i in range(4):
  514. x3, y3 = points[i]
  515. x4, y4 = points[(i + 1) % 4]
  516. denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
  517. nua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)
  518. nub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)
  519. if denom == 0:
  520. # This covers two cases:
  521. # nua == nub == 0: Coincident
  522. # otherwise: Parallel
  523. continue
  524. ua, ub = nua / denom, nub / denom
  525. if 0 <= ua <= 1 and 0 <= ub <= 1:
  526. x = x1 + ua * (x2 - x1)
  527. y = y1 + ua * (y2 - y1)
  528. m = QtCore.QPoint((x3 + x4) / 2, (y3 + y4) / 2)
  529. d = labelme.utils.distance(m - QtCore.QPoint(x2, y2))
  530. yield d, i, (x, y)
  531. # These two, along with a call to adjustSize are required for the
  532. # scroll area.
  533. def sizeHint(self):
  534. return self.minimumSizeHint()
  535. def minimumSizeHint(self):
  536. if self.pixmap:
  537. return self.scale * self.pixmap.size()
  538. return super(Canvas, self).minimumSizeHint()
  539. def wheelEvent(self, ev):
  540. if QT5:
  541. mods = ev.modifiers()
  542. delta = ev.angleDelta()
  543. if QtCore.Qt.ControlModifier == int(mods):
  544. # with Ctrl/Command key
  545. # zoom
  546. self.zoomRequest.emit(delta.y(), ev.pos())
  547. else:
  548. # scroll
  549. self.scrollRequest.emit(delta.x(), QtCore.Qt.Horizontal)
  550. self.scrollRequest.emit(delta.y(), QtCore.Qt.Vertical)
  551. else:
  552. if ev.orientation() == QtCore.Qt.Vertical:
  553. mods = ev.modifiers()
  554. if QtCore.Qt.ControlModifier == int(mods):
  555. # with Ctrl/Command key
  556. self.zoomRequest.emit(ev.delta(), ev.pos())
  557. else:
  558. self.scrollRequest.emit(
  559. ev.delta(),
  560. QtCore.Qt.Horizontal
  561. if (QtCore.Qt.ShiftModifier == int(mods))
  562. else QtCore.Qt.Vertical)
  563. else:
  564. self.scrollRequest.emit(ev.delta(), QtCore.Qt.Horizontal)
  565. ev.accept()
  566. def keyPressEvent(self, ev):
  567. key = ev.key()
  568. if key == QtCore.Qt.Key_Escape and self.current:
  569. self.current = None
  570. self.drawingPolygon.emit(False)
  571. self.update()
  572. elif key == QtCore.Qt.Key_Return and self.canCloseShape():
  573. self.finalise()
  574. def setLastLabel(self, text):
  575. assert text
  576. self.shapes[-1].label = text
  577. self.shapesBackups.pop()
  578. self.storeShapes()
  579. return self.shapes[-1]
  580. def undoLastLine(self):
  581. assert self.shapes
  582. self.current = self.shapes.pop()
  583. self.current.setOpen()
  584. if self.createMode in ['polygon', 'linestrip']:
  585. self.line.points = [self.current[-1], self.current[0]]
  586. elif self.createMode in ['rectangle', 'line', 'circle']:
  587. self.current.points = self.current.points[0:1]
  588. elif self.createMode == 'point':
  589. self.current = None
  590. self.drawingPolygon.emit(True)
  591. def undoLastPoint(self):
  592. if not self.current or self.current.isClosed():
  593. return
  594. self.current.popPoint()
  595. if len(self.current) > 0:
  596. self.line[0] = self.current[-1]
  597. else:
  598. self.current = None
  599. self.drawingPolygon.emit(False)
  600. self.repaint()
  601. def loadPixmap(self, pixmap):
  602. self.pixmap = pixmap
  603. self.shapes = []
  604. self.repaint()
  605. def loadShapes(self, shapes, replace=True):
  606. if replace:
  607. self.shapes = list(shapes)
  608. else:
  609. self.shapes.extend(shapes)
  610. self.storeShapes()
  611. self.current = None
  612. self.repaint()
  613. def setShapeVisible(self, shape, value):
  614. self.visible[shape] = value
  615. self.repaint()
  616. def overrideCursor(self, cursor):
  617. self.restoreCursor()
  618. self._cursor = cursor
  619. QtWidgets.QApplication.setOverrideCursor(cursor)
  620. def restoreCursor(self):
  621. QtWidgets.QApplication.restoreOverrideCursor()
  622. def resetState(self):
  623. self.restoreCursor()
  624. self.pixmap = None
  625. self.shapesBackups = []
  626. self.update()